Java File / IO / NIO API,用于写入可由其他程序实时读取的文件

时间:2015-04-20 20:40:53

标签: java logging file-io nio tail

我正在使用Java控制台应用程序,该应用程序必须写入(追加)两个单独的文件,对应于OUTERR个流。 tailgrep等外部实用程序将实时监控这些文件。我开始通过Appendable接口写入这两个流,但是在应用程序完成执行之后,在输出流上刷新并关闭后,文件似乎不会反映任何更改。

服务

package com.mycompany;

public class Service {

                private Appendable outlog;
                private Appendable errlog;

                public Service(Appendable outlog, Appendable errlog) {
                        this.outlog = outlog;
                        this.errlog = errlog;
                }

                public void executeTask() throws Exception {

                                outlog.append("task execution started\n");
                                Thread.sleep(30 * 1000);
                                outlog.append("task execution completed\n");
                }
}

应用

package com.mycompany;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;

public class Application {

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

                PrintWriter outlog = new PrintWriter(new BufferedWriter(new FileWriter("application.log")));
                PrintWriter errlog = new PrintWriter(new BufferedWriter(new FileWriter("application-err.log")));

                Service service = new Service(outlog, errlog);
                service.executeTask();

                outlog.flush();
                outlog.close();
                errlog.flush();
                errlog.close();
        }
}

我的设计是否存在根本错误,或者我应该以更好,更有效的方式做到这一点?

1 个答案:

答案 0 :(得分:0)

Service班级中,将outlogerrlog字段声明并传播为Writer(实现Appendable)并致电outlog.flush()在给你发消息之后。

public class Service {

  private Writer outlog;
  private Writer errlog;

  public Service(Writer outlog, Writer errlog) {
    this.outlog = outlog;
    this.errlog = errlog;
  }

  public void executeTask() throws Exception {
    try {
      outlog.append("task execution started\n");
      outlog.append("task execution completed\n");
    finally {
      outlog.flush();
    }
  }
}