Java 文件移动不工作
我使用以下方法将文件从一个文件夹(源)移动到另一个文件夹(目标)。我添加了一个检查,以查看文件是否存在并返回true,但文件仍然没有移动到目标 这里的源路径是: C:\App\u v10.4\RAP009.jrxml和C:\App\u v10.4\RAP009.jasperJava 文件移动不工作,java,file-io,java-io,Java,File Io,Java Io,我使用以下方法将文件从一个文件夹(源)移动到另一个文件夹(目标)。我添加了一个检查,以查看文件是否存在并返回true,但文件仍然没有移动到目标 这里的源路径是: C:\App\u v10.4\RAP009.jrxml和C:\App\u v10.4\RAP009.jasper private void moveFile(List<String> source, String destination) throws IOException { if (null
private void moveFile(List<String> source, String destination)
throws IOException {
if (null != source && !source.isEmpty()) {
for (String path : source) {
try {
File file = new File(path);
System.out.println(path);
System.out.println("File :" + file.exists());
System.out.println(new File(destination + file.getName()));
System.out.println(file.getCanonicalPath());
System.out.println(file.getAbsolutePath());
System.out.println(file.getPath());
if (file.renameTo(new File(destination + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File has failed to move!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
目的地:
C:\Users\Avijit\Desktop\RAP009.jrxml和C:\Users\Avijit\Desktop\RAP009.jasper
private void moveFile(List<String> source, String destination)
throws IOException {
if (null != source && !source.isEmpty()) {
for (String path : source) {
try {
File file = new File(path);
System.out.println(path);
System.out.println("File :" + file.exists());
System.out.println(new File(destination + file.getName()));
System.out.println(file.getCanonicalPath());
System.out.println(file.getAbsolutePath());
System.out.println(file.getPath());
if (file.renameTo(new File(destination + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File has failed to move!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
根据美国石油学会的api
“此方法行为的许多方面本质上依赖于平台:重命名操作可能无法将文件从一个文件系统移动到另一个文件系统,它可能不是原子的,如果目标抽象路径名已存在,则可能无法成功。应始终检查返回值,以确保重命名操作成功。”
因此,使用renameTo
时会出现警告
但是,您的案例可能会遇到另一个问题。如果目录结构不存在,它将失败。在Java 7中,这是用修复的。此方法将提供更可靠的性能,即使子目录不存在,但问题并不是罪魁祸首。您有对目标控制器的写访问权限吗是吗?谢谢你看,是的,我有目标目录的写权限。。。