gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:02:42 24 4
gpt4 key购买 nike

每次修改文件时我都想在文件末尾写一些东西,我正在使用这段代码:

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(计数器 + 内容);

最佳答案

您线程的写入导致对文件的进一步更改。自馈环。

关于java - 如何从一个线程只写入一次文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30763531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com