假设我有 105条记录,我想在文本文件中写下所有记录,其中每个文件中将有 10条记录。
所以总文件将在这里生成11.
答案 0 :(得分:0)
Try this
int count = 0; String filename = "text1";
for (int i = 0; i <= 105; i++) // loop to 105 times
{
count++;
if(count <= 10) //write 10 records to the file
{
if(count == 1)
filename = "text" + (i/10);
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)))) {
out.println("the text");
}catch (IOException e) {}
if(count == 10)
count = 0;
}
}
答案 1 :(得分:0)
public static void writeToMultipleFiles(int numberOfLines, String prefix, List<String> records){
lineCounter = 1;
counter = 1;
String filename = prefix + counter;
for (String line : records){
if(lineCounter = numberOfLines){
lineCounter = 1;
counter++;
filename = prefix + counter;
}
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)))) {
out.println(line);
lineCounter++;
}catch (IOException e) {}
}
}