不打印到文件 java

Not printing to file java

我正在尝试记录我的程序正在做什么。目前我正在使用 PrintWriter 但它只生成一个空白的 txt 文件。如果可能,有人可以更正我的代码或提出任何建议吗?

    public class Log {
public static void log(String string){
    if(string != null) {
        System.out.println("log ".concat(string));
        try {
            PrintWriter out=new PrintWriter(new FileWriter("log.txt"));
            out.println("log ".concat(string));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static void log(String[] strings) {
    if (strings == null) return;
    for(String string : strings) {
        if (string != null) {
            System.out.println("log ".concat(string));
            try {
                PrintWriter out=new PrintWriter(new FileWriter("log.txt"));
                out.println("log ".concat(string));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

您必须刷新 PrintWriter 才能将数据写入文件

PrintWriter out = new PrintWriter(new FileWriter("log.txt"));
out.println("log ".concat(string));
out.flush();

如果您完成了写入文件,您应该关闭 PrintWriter,这也会导致写入数据

out.close();

您必须关闭文件。像这样:

PrintWriter out=new PrintWriter(new FileWriter("log.txt"));
out.println("log ".concat(string));
out.close();

顺便说一句,您可以使第二种方法更简洁:

public static void log(String[] strings) {
    if (strings == null) return;
    for(String string : strings) {
        log(string);
    }
}

任何时候复制粘贴相同的代码时,您都应该寻找一种使用封装/方法调用来删除重复代码的方法。如果需要,这将使以后更改内容变得更容易。