我正在尝试并尝试制作一个程序,将所有文件从我的D:\ Downloads目录中作为安装程序移动到我的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();
}
}
}
}
}
}
提前致谢!
答案 0 :(得分:0)
尝试更改每个文件的文件名,如果文件名可更改,则任何其他进程都不会使用该文件。你不能用眼睛追踪它,因为可以有任何使用它的线程。检查完每个文件后,移动它。
File sourceFile = ...;
boolean changeableSource = source.renameTo(sourceFile);
File destFile = ...;
boolean changeableSource = destFile.renameTo(destFile);
if(changeableSource && changeableSource ){
//Moving here...
}