日期:2014-05-20  浏览次数:20754 次

如何用Java分割大txt文件?
我的想法是按字符长度读取一个文本文件的内容,
先读取0~2000个字符,再读取2001~4000的字符!
然后分别保存为每个小文件,以此类推!
请问该怎么实现?

------解决方案--------------------
可以参考如下代码
file的地址可以自己填进去,新建的文件名自己也可以更改
size就是你想读取的字符个数

Java code
package com.ray.tests.cutfile;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class CutFile {
    public static void main(String[] args) throws IOException {
        cutFile("src/com/ray/tests/cutfile/file.txt", 2000);
    }
    
    public static void cutFile(String fileName, int size) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
        
        int len;
        int count = 1;
        char[] cbuf = new char[size];
        while ((len = reader.read(cbuf, 0, size)) != -1) {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName + "_" + count)));
            writer.write(cbuf, 0, len);
            writer.flush();
            writer.close();
            count++;
        }
    }
}