Java FileWriter 跳过文件
我有一个带有文件的软件包:“ 100.txt”,“ 1000.txt”,“ 10000.txt”,“ 100000.txt”,“ 1000000.txt”。 但是,当我启动程序时,它会跳过100和1000个TXT文件。你能告诉我为什么吗?
public void generateData(Path path) throws IOException {
for (int i = 1; i <= 5; i++){
for (int j = 100; j <= 1000000; j*=10){
FileWriter fileWriter = new FileWriter(path.resolve(Integer.toString(i)).resolve(j + ".txt").toFile());
Random random = new Random();
for (int k = 0; k < j; k++){
int num = random.nextInt(10);
fileWriter.write(num);
fileWriter.write("\n");
}
}
}
}
I have a package with files : "100.txt" ,"1000.txt", "10000.txt","100000.txt", "1000000.txt".
But when i launch my program, it skips 100 and 1000 txt files. Can you tell me why?
public void generateData(Path path) throws IOException {
for (int i = 1; i <= 5; i++){
for (int j = 100; j <= 1000000; j*=10){
FileWriter fileWriter = new FileWriter(path.resolve(Integer.toString(i)).resolve(j + ".txt").toFile());
Random random = new Random();
for (int k = 0; k < j; k++){
int num = random.nextInt(10);
fileWriter.write(num);
fileWriter.write("\n");
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我运行了你的代码,一切似乎都运行得很好。
所有文件均已打印:
我注意到的一件事是,在完成后您不会关闭
FileWriter
。也许这就是问题所在。这是我运行的完整代码。我确实删除了将文件写入编号目录的操作,因为这些目录在我的计算机上不存在。
根据安迪的建议,使用 try-with-resources 的解决方案。
I ran your code and everything seemed to run pretty well.
All files were printed:
One thing I noticed is that you don't close your
FileWriter
after you're done with it. Perhaps that is the problem.Here is the full code I ran. I did remove the writing of the files into the numbered directories since those directories didn't exist on my machine.
Based on Andy's suggestion a solution that uses a try-with-resources.