首页 > 解决方案 > 写入字体文件

问题描述

我需要创建一个方法,给定文件名和整数 n 写入具有该名称的字符文件,n 个随机整数,每行一个。这是我的代码,我认为它编写正确,但我传递的文件仍然是“空”的,大小为 0 字节。有人能帮我吗?

   public static void scriviIntero(String nomeFile, int n) {
    try (PrintWriter scrivi = new PrintWriter(new FileWriter(nomeFile, true))) {
    Random random = new Random();
        for (int i = 0; i < n; i++) {
            int nuovo = random.nextInt(99999);
            scrivi.println(nuovo);
        }
    } catch (IOException e) {
        System.out.println("Errore di I/O nella funzione scriviIntero nel tentativo di scrivere sul file " + nomeFile);
    }
    
}

标签: javafilewriting

解决方案


你的问题是不正确的初始化FileWriter。看看我放的地方true

public static void main(String[] args) throws IOException {
    appendRandomNumbersToFile("e:/foo.txt", 10);
    appendRandomNumbersToFile("e:/foo.txt", 20);
}

public static void appendRandomNumbersToFile(String fileName, int n) throws IOException {
    if (n <= 0)
        throw new RuntimeException("n should be positive");

    try (PrintWriter writer = new PrintWriter(new FileWriter(fileName, true))) {
        Random random = new Random();

        for (int i = 0; i < n; i++)
            writer.println(random.nextInt());
    }
}

PS这是来自JavaDoc:

public FileWriter(String fileName, boolean append) {}
public PrintWriter(Writer out, boolean autoFlush) {}

推荐阅读