写字体文件

问题描述

我需要创建一个给定文件名的方法,并将整数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);
    }
    
}

解决方法

您的问题是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());
    }
}

P.S。。来自JavaDoc:

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