如何只从线程写入一次文件?

时间:2015-06-10 17:39:01

标签: java multithreading

我想在每次修改文件时在文件的末尾写一些内容并且我使用此代码:

public class Main {

    public static final String DIRECTORY_TO_WATCH = "D:\\test";

    public static void main(String[] args) {
        Path toWatch = Paths.get(DIRECTORY_TO_WATCH);
        if (toWatch == null) {
            throw new UnsupportedOperationException();
        }
        try {
            WatchService myWatcher = toWatch.getFileSystem().newWatchService();
            FileWatcher fileWatcher = new FileWatcher(myWatcher);
            Thread t = new Thread(fileWatcher, "FileWatcher");
            t.start();
            toWatch.register(myWatcher, StandardWatchEventKinds.ENTRY_MODIFY);
            t.join();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

和线程类:

public class FileWatcher implements Runnable{
    private WatchService myWatcher;
    private Path toWatch;
    String content = "Dong\n";
    int counter = 0;

    public FileWatcher (WatchService myWatcher, Path toWatch) {
    this.myWatcher = myWatcher;
    this.toWatch = toWatch;
}
    @Override
    public void run() {
        try {
            WatchKey key = myWatcher.take();
            while (key != null) {
                for (WatchEvent event : key.pollEvents()) {
                    //System.out.printf("Received %s event for file: %s\n", event.kind(), event.context());
                    //System.out.println(counter);
                    myWatcher = null;
                    File file = new File(Main.DIRECTORY_TO_WATCH + "\\" + event.context());
                    FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
                    fw.write(counter + content);
                    fw.close();
                    counter++;
                    myWatcher = toWatch.getFileSystem().newWatchService();
                    toWatch.register(myWatcher, StandardWatchEventKinds.ENTRY_MODIFY);
//                  BufferedWriter bwWriter = new BufferedWriter(fw);
//                  bwWriter.write(content);
//                  bwWriter.close();
                }
                key.reset();
                key = myWatcher.take();
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

我想在文件中输入:

acasc 0dong
dwqcacesv 1dong
terert 2dong

然而,现在我得到了这个,因为它在文件中写了太多次:

acasc 0dong
1dong
...
50123dong

如果我使用System.out.println(counter);它可以正常工作(正确打印文件更改次数),但在fw.write(counter + content);

1 个答案:

答案 0 :(得分:0)

您的线程写入会导致文件的进一步更改。 自给自足循环。