Java FileWriter 跳过文件

Java FileWriter skip files

我有一个文件包:“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");
                }
            }
        }
    }

我 运行 你的代码和一切似乎 运行 都很好。

已打印所有文件:

  • 100.txt
  • 1000.txt
  • 10000.txt
  • 100000.txt
  • 1000000.txt

我注意到的一件事是,您在完成后不会关闭 FileWriter。也许这就是问题所在。

这是我的完整代码运行。我确实删除了将文件写入编号目录的操作,因为这些目录在我的机器上不存在。

package forloop;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;

public class GenerateData {

    public static void main(String[] args) throws IOException {

        Path path = Paths.get("");

        generateData(path);
    }

    public static 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(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");
                }
                fileWriter.close();
            }
        }
    }
}

根据 Andy 的建议,解决方案使用 try-with-resources。

package forloop;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;

public class GenerateData {

    public static void main(String[] args) throws IOException {

        Path path = Paths.get("");

        generateData(path);
    }

    public static void generateData(Path path) throws IOException {
        for (int i = 1; i <= 5; i++) {
            for (int j = 100; j <= 1000000; j*=10) {
                try (FileWriter fileWriter = new FileWriter(path.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");
                    }
                }
            }
        }
    }
}