2

FileHandler一旦线程完成或强制完成,我想关闭所有s 。
我创建了一个closeLogger函数,但它似乎没有被调用
,因为我看到该文件仍被锁定在文件夹中。

  1. 问题是什么?
  2. 如果我在eclipse中强行终止执行,我也可以处理吗?

我的代码如下:

public class Passenger extends Thread {

    private Logger logger;

    public Passenger() throws SecurityException, IOException, InterruptedException {
        logger = Logger.getLogger(String.format("Passenger%sLogger", name));
        FileHandler fileHandler = new FileHandler(String.format(".\\Logs\\PassengerLogs\\passenger_%s.txt", name), true);
        fileHandler.setFormatter(new LogFormatter());
        logger.addHandler(fileHandler);
    }

    @Override
    public void run() {
        try {
            goToStation();
            waitForTaxi();
            if (passengerState == PassengerState.WatingInQueue) {
                goHome();
            } else { // already in taxi
                synchronized (this) {
                    wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            closeLogger();
        }
    }

    private void closeLogger() {
        Logger logger = getLogger();
        java.util.logging.Handler[] handlers = logger.getHandlers();
        for (java.util.logging.Handler h : handlers) {
            try {
                h.close();
            } catch (SecurityException e) {}
        }
    }
}
4

1 回答 1

2

由于您使用 addHandler() 添加处理程序,因此干净的方法是 close() 然后调用 removeHandler()

见 removeHandler

另外,从上面的链接复制:

After passing this initial (cheap) test, the Logger will allocate a LogRecord to describe the logging message. It will then call a Filter (if present) to do a more detailed check on whether the record should be published. If that passes it will then publish the LogRecord to its output Handlers. By default, loggers also publish to their parent's Handlers, recursively up the tree.

So if you are not removing handler, it will still hold reference. This may be the reason why your file is still locked. Try this and let me know if it works!

于 2012-05-15T14:45:44.217 回答