未将同一文件追加到使用单一实例报告器类



我想在应用程序运行进程时附加到单个文件。这是日志记录类型功能(记录到单个文件)的一个非常简单的要求。但我不确定为什么我只得到文件中最后一个附加的值。其他台词呢。

在文件输出中,我只看到 1 行:"进程 2 已执行"。我希望看到一个对应于这些行中的每一行(executor.execute();),如main方法所示。

主要方法:

    public static void main(String args[]){
        ProcessExecutor executor = new ProcessExecutor();
        executor.execute();
        executor.execute();
        executor.execute();
        ProcessExecutorTwo executor2 = new ProcessExecutorTwo();
        executor2.execute();
        executor2.execute();
    }
}

进程执行器使用报告器:

// identical to executorOne
public class ProcessExecutorTwo {
private Reporter processTwoReporter; 
    public ProcessExecutorTwo(){
        processTwoReporter = Reporter.getInstance("executor.out");
    }
    public void execute(){
        System.out.println("executing..");
        // .... code taken out
        processTwoReporter.write("process 2 has Executed");
    }
}

报告器类是单例:

public class Reporter {
    private final String headQuartersFile;
    private static Reporter instance;

    private Reporter(String logFile){
        this.headQuartersFile = logFile;
    }
    public static Reporter getInstance(String headQuartersFile){
        synchronized(Reporter.class){
            if(instance==null){
                instance = new Reporter(headQuartersFile);
            }
        }
        return instance;
    }
    public void write(String data) {
        PrintWriter out;
        try {
            out = new PrintWriter(new BufferedWriter(new FileWriter(this.headQuartersFile)), true);
            out.append(data);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如果您希望write方法附加到现有文件的末尾而不是覆盖它,则需要使用 FileWriter(File file, boolean append) 构造函数:

out = new PrintWriter(new BufferedWriter(new FileWriter(this.headQuartersFile,true)), true);

代码中已有的true标志位于对PrintWriter构造函数的调用中,它具有不同的用途(自动刷新)。

最新更新