分割文件行数

可以将一个大文件分割成小文件,每个指定行数

package com.example;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class SplitFile20180522 {

    public static void main(String[] args) throws IOException {
        String filePath = "D:\\downloads\\split\\20180521-3.csv";
        boolean skipFirstLine = true;
        int linePerFile = 10000000;
        System.out.println(filePath);
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            int lineCount = 0;
            int writeFileCount = 1;
            FileWriter fileWriter = null;
            if (skipFirstLine) {
                br.readLine();
            }
            while ((line = br.readLine()) != null) {
                lineCount++;
                if (fileWriter == null) {
                    fileWriter = new FileWriter(filePath + "_" + writeFileCount, false);
                }
                fileWriter.write(line + "\r\n");
                if (lineCount % linePerFile == 0) {
                    System.out.println("write file " + writeFileCount + " done");
                    fileWriter.close();
                    fileWriter = null;
                    writeFileCount++;
                }
            }
            if (fileWriter != null) {
                System.out.println("write file " + writeFileCount + " done");
                fileWriter.close();
            }
        }
    }

}

2 thoughts on “分割文件行数

Leave a Reply

Your email address will not be published. Required fields are marked *