java - 尝试在目录之间 move 时文件正在使用异常

标签 java file move

只是为了好玩,我正在尝试并尝试制作一个程序,将所有文件从我的 D:\Downloads 目录(安装程序) move 到我的 G:\Downloads\Installers 目录。我以为我可以正常工作,但是在使用它时,它返回“该进程无法访问该文件,因为它正在被另一个进程使用。”

这是代码,如有任何意见,我们将不胜感激。

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class FileOrganizer { 

public static void main(String[] args) {

File folder = new File("d:/Downloads");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
      String name = listOfFiles[i].getName();
      if (name.indexOf("Setup") > -1) {
          Path source = Paths.get("d:/Downloads");
          Path target = Paths.get("g:/Downloads/Installers");         
          try {
              Files.move(source, 
                         target.resolve(source.getFileName())), 
                         StandardCopyOption.REPLACE_EXISTING);}
               catch (IOException e) {
                  e.printStackTrace();
              }
          }
    }
    }  
    }     
    }

提前致谢!

最佳答案

尝试更改每个文件的文件名,如果文件名可更改,则该文件不会被任何其他进程使用。你无法用眼睛追踪它,因为任何线程都可以使用它。检查每个文件后, move 它。

File sourceFile = ...;      
boolean changeableSource = source.renameTo(sourceFile);

File destFile = ...;
boolean changeableSource = destFile.renameTo(destFile);

if(changeableSource && changeableSource ){
   //Moving here...
}

关于java - 尝试在目录之间 move 时文件正在使用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13282542/

相关文章:

python - 使用 fnmatch 排除文件

java - 递归 move 和重命名文件和文件夹的 ANT 任务

move - 在shutil.move 操作期间覆盖目录中已存在的文件

python - 在python中多次从文件中的一个特定单词读取到文件中的另一个特定单词

unix - 在shell脚本中确定文件的年龄

c++ - "Inheriting" move 运算符?

javascript - 使用高效算法对数组中的相同对进行计数

java - 为 jar 和类设置类路径

JavaScript异常 : (TypeError): Object doesn't support this property or method

java - 保存位图时设置日期