java - 重命名文件在线程 "main"java.nio.file.FileSystemException : 中抛出异常

标签 java file

我正在使用 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/

相关文章:

java - 如何使用 JFreeChart 在外部 Tomcat 中运行报告?

java - 为什么要解释java字节码?

database - 将哈希写入文件的最佳方法

java - 从有条件的文本文件中读取

java - Flyway使用java类对sql文件进行排序

java - 是否可以在分布式环境中将 RMI 与循环负载均衡器一起使用?

java - 我的电脑无法安装 Java

javascript - FileReader readAsDataURL 无法读取图像文件

c - 将文件名打印到标准输出

windows - 为什么我只能在 Windows 上使用 Tie::File 打开 2045 个文件?