欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

IO流切割过大文件代码

程序员文章站 2022-03-27 07:51:37
...

先查出总行数,之后再以总行数分割文件
import java.io.*;
public class GetRows {

    public static void main(String args[]) {
        try {
            FileReader read = new FileReader("D:/解绑记录.csv");
            BufferedReader br = new BufferedReader(read);
            String row;

            int rownum = 1;
            while ((row = br.readLine()) != null) {
                rownum ++;
            }
            System.out.println("rownum="+rownum);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

开始分割文件,注意 readline方法是自动换行;
import java.io.*;
public class CutFile {

    public static void main(String args[]) {
        try {
            FileReader read = new FileReader("D:/解绑记录.csv");
            BufferedReader br = new BufferedReader(read);
            String row;

            int rownum = 1;

            int fileNo = 1;
            FileWriter fw = new FileWriter("D:/解绑记录"+fileNo +".csv");
            String rowOne = br.readLine();  //由于每个切割文件都需要记录第一行标题,这边将它记录下来,,
            fw.append(rowOne + "\r\n");
            while ((row = br.readLine()) != null) {
                rownum ++;
                fw.append(row + "\r\n");

                if((rownum / 156566) > (fileNo - 1)){
                    fw.close();
                    fileNo ++ ;
                    fw = new FileWriter("D:/解绑记录"+fileNo +".csv");
                    fw.append(rowOne + "\r\n");
                }
            }
            fw.close();
            System.out.println("rownum="+rownum+";fileNo="+fileNo);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
相关标签: JAVA切割文件