也许是个愚蠢的问题。但我尝试用 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
and a BufferedWriter
has .newLine()
.
因此替换为:
writer.write(line);
writer.newLine();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)