【发布时间】:2023-04-09 22:40:01
【问题描述】:
也许是愚蠢的问题。但我尝试用 512 个整数填充一个空文本文件,每个整数都在新行上。我能够将它们随机化并将它们写入文件,但它们会产生大量我想要的数字。谁能帮我更正我的代码?
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class Randomizer {
public static void main() {
// The target file
File out = new File("random.txt");
FileWriter fw = null;
int n = 512;
// Try block: Most stream operations may throw IO exception
try {
// Create file writer object
fw = new FileWriter(out);
// Wrap the writer with buffered streams
BufferedWriter writer = new BufferedWriter(fw);
int line;
Random random = new Random();
while (n > 0) {
// Randomize an integer and write it to the output file
line = random.nextInt(1000);
writer.write(line + "\n");
n--;
}
// Close the stream
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
}
运行结束时random.txt的内容: 9463765593113665333437829621346187993554694651813319223268147794541131427390等
【问题讨论】:
-
您使用的是什么操作系统?在 Windows 上,换行符是
\r\n,而不是\n。 -
我猜输出是正确的,你是用记事本查看文件内容吗?一些编辑器不会将
\n读作换行符,而是使用\r\n。 -
您使用的是哪个版本的 Java?
标签: java file text file-io random