gpt4 book ai didi

java - 使用 Java 在文件中打印 132000 行

转载 作者:行者123 更新时间:2023-12-03 21:41:09 25 4
gpt4 key购买 nike

我正在尝试在一个文件中打印 132_000 行。

这是我的代码:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Random;
import java.util.Scanner;

public class CredentialTemplate {

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

// Declaring output file
File fout = new File(
"D:\\testout.txt");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

int start = 0, stop = 0;
Scanner x = new Scanner(System.in);
System.out.print("Start: ");
start = x.nextInt();
System.out.print("End: ");
stop = x.nextInt();

Random r = new Random();

for (int i = start; i <= stop; i++) {

System.out.println("Importeduser" + i + ",Test,4," + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9) + r.nextInt(9)+ r.nextInt(9)+",0,"
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9) + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9) + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9));
bw.write("Importeduser" + i + ",Test,4," + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9) + r.nextInt(9)+ r.nextInt(9)+",0,"
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9) + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9) + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9));
bw.newLine();

}

}

}

我面临的问题:我没有得到 txt 文件中的所有 1,32,000 行。有时是 1,31,693 行或 1,31,721 行。

但在控制台中我可以看到所有打印的 1,32,000。

如果我在这里做错了什么,请告诉我。

提前致谢。

最佳答案

您没有关闭您的Writer。您可以使用 finally block ,也可以使用 try-with-resources .第一个可能看起来像,

try {
for (int i = start; i <= stop; i++) {
String line = "Importeduser" + i + ",Test,4," + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + ",0," + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9);
System.out.println(line);
bw.write(line);
bw.newLine();
}
} finally {
if (bw != null) {
bw.close();
}
if (fos != null) {
fos.close();
}
}

第二个(try-with-resources)可能看起来像

try (FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
fos))) {
for (int i = start; i <= stop; i++) {
String line = "Importeduser" + i + ",Test,4," + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + ",0," + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9)
+ r.nextInt(9) + r.nextInt(9) + r.nextInt(9);
System.out.println(line);
bw.write(line);
bw.newLine();
}
}

关于java - 使用 Java 在文件中打印 132000 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29470233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com