如何用java IO流把一个2万行数据的文件拆分成40个小文件(每个文件500笔数据)?小弟刚学IO请高手帮忙解答

谢谢了!!
2024-12-22 16:27:59
推荐回答(2个)
回答1:

你试一下,如有问题再联系。没做出两万条数据。
--------------------------------------------------------------------------
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.DecimalFormat;
import java.util.Random;

public class Test {

public static void main(String[] args) throws Exception {

File src = new File("D:\\src.txt");
File dest = new File("D:\\dest");
FileReader fr = new FileReader(src);
BufferedReader br = new BufferedReader(fr);
int lineno = 1;
int index = 1;
dest.mkdirs();
FileWriter fw = new FileWriter(new File(dest, creIndex(index++)
+ ".txt"));
while (br.ready()) {
if (lineno++ % 500 == 0) {
fw.close();
fw = new FileWriter(new File(dest, creIndex(index++) + ".txt"));
}
String line = br.readLine();
fw.write(line + "\r\n");
}
fw.close();
br.close();
fr.close();
}

public static String creIndex(int num) {
DecimalFormat df = new DecimalFormat("00");
return df.format(num);
}

}

回答2:

public static void main(String arg[]) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream("F:\\1.txt")));
String temp = null;
int tt = 0;
while((temp = br.readLine()) != null){
if(tt % 500 == 0){
if(bw != null)
bw.close();
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("F:\\1"+tt+".txt")));
}
bw.write(temp);
}
br.close();
bw.close();
} catch (Exception e) {
}
}