愚蠢的问题,也许吧。但我尝试用 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等
最佳答案
writer.write(line + "\n");
不要使用它。
您使用一个 BufferedWriter
并且一个 BufferedWriter
有 .newLine()
。
因此替换为:
writer.write(line);
writer.newLine();
关于java - 在 Java 中创建一个充满随机整数的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30284921/