我试图在文件中打印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文件中所有的132000行。有时是1,31,693行或1,31,721行。
但是在控制台上,我可以看到所有的132000张打印。
如果我做错了什么,请告诉我。
提前谢谢。
发布于 2015-04-06 11:26:25
你不能关闭你的Writer。您可以使用finally块,也可以使用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();
}
}发布于 2015-04-06 11:26:15
关闭写入器以写入其余数据。
在程序结束时执行bw.close()
https://stackoverflow.com/questions/29470233
复制相似问题