我正在使用 WatchService. 查找用于创建新文件的目录每当创建新文件或进入此目录时,我都需要更改该文件的名称。
我有以下代码
Path pathfolder=Paths.get("D:\\tempm\\watch");
WatchService watcherService=FileSystems.getDefault().newWatchService();
pathfolder.register(watcherService, StandardWatchEventKinds.ENTRY_CREATE);
System.out.println("Watching that directory");
boolean valid=true;
do{
WatchKey watchKey=watcherService.take();
for(WatchEvent<?> event:watchKey.pollEvents()){
WatchEvent.Kind kind=event.kind();
if(StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())){
final String fileName=event.context().toString();
if(fileName.endsWith(".jar")){
System.out.println("File created--"+fileName);
File oldFileName=new File("D:\\tempm\\watch\\"+fileName);
File destFile=new File("D:\\tempm\\watch\\"+fileName.substring(0,fileName.lastIndexOf("."))+"_processing.jar");
File path=new File("D:\\tempm\\watch\\");
if(!fileName.contains("_processing")){
Files.move(oldFileName.toPath(), destFile.toPath(),StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING); //Line Number 45
FileDeleteStrategy.FORCE.delete(oldFileName);
System.out.println("Old file deleted");
}
}
}
}
valid=watchKey.reset();
}while(valid);
当我第一次将文件粘贴到该目录时,它已成功重命名。如果我第二次添加任何文件,它会抛出异常。我不知道为什么会出现此异常。需要一些帮助。
我的输出
Watching that directory
File created--dom4j.jar
Old file deleted
File created--dom4j_processing.jar
File created--watchplc.jar
Exception in thread "main" java.nio.file.FileSystemException: D:\tempm\watch\watchplc.jar -> D:\tempm\watch\watchplc_processing.jar: The process cannot access the file because it is being used by another process.
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileCopy.move(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.move(Unknown Source)
at java.nio.file.Files.move(Unknown Source)
at ext.gt.test.MonitorDirectory.main(MonitorDirectory.java:45)
最佳答案
您的程序失败,因为StandardWatchEventKinds.ENTRY_CREATE
仅告诉您文件已创建,而不是进程已停止写入文件或释放文件句柄。您可以通过自己创建一个简单的程序来复制该错误。
public class FileCreator
{
public static void main(String... args)
{
new FileCreator().go();
}
public void go()
{
FileWriter fileWriter = null;
try
{
File file = new File("d:/tempm/watch/" + System.currentTimeMillis() + ".jar");
fileWriter = new FileWriter(file);
for (int counter = 0; counter < 100; counter++)
{
// first write
fileWriter.write(String.valueOf(System.nanoTime()));
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(fileWriter != null)
{
try
{
// data is flushed and file handles are closed
fileWriter.flush();
fileWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
请注意,一旦遇到第一个 write()
就会创建一个文件。该程序仍然拥有该文件的句柄,并继续写入该文件,直到流被刷新并关闭。您的其他程序会在该文件上的流关闭之前拾取该文件并移动它。
您需要一个系统,在您尝试对文件进行移动
之前,告诉您文件是否已完全写入您正在监视的目录。
关于java - 重命名文件在线程 "main"java.nio.file.FileSystemException : 中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21827789/