文件移动不起作用

时间:2013-04-10 17:09:28

标签: java file-io java-io

我正在使用以下方法将文件从一个文件夹(源)移动到另一个文件夹(目标)。我添加了一个检查,看看文件是否存在,返回true,但文件仍未移动到目标。

这里的源路径是:

C:\ App_v10.4 \ RAP009.jrxml和C:\ App_v10.4 \ RAP009.jasper

目的地:

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();
            }
        }
    }

}

控制台O / P:

C:\App_v10.4\RAP009.jrxml

File :true
C:\Users\Avijit\Desktop\RAP009.jrxml

C:\App_v10.4\RAP009.jrxml

C:\App_v10.4\RAP009.jrxml

C:\App_v10.4\RAP009.jrxml

File has failed to move!

C:\App_v10.4\RAP009.jasper

File :true

C:\Users\Avijit\Desktop\RAP009.jasper

C:\App_v10.4\RAP009.jasper

C:\App_v10.4\RAP009.jasper

C:\App_v10.4\RAP009.jasper

File has failed to move!

1 个答案:

答案 0 :(得分:0)

根据File的api,

&#34;此方法行为的许多方面本质上都依赖于平台:重命名操作可能无法将文件从一个文件系统移动到另一个文件系统,它可能不是原子的,如果重命名操作可能不成功,目标抽象路径名的文件已存在。应始终检查返回值以确保重命名操作成功。&#34;

因此使用renameTo时会出现警告。

但是你的情况很可能还会遇到另一个问题。如果目录结构不存在,则会失败。在Java 7中,这是通过Files.move修复的。这种方法将提供稍微更可靠的性能,即使子目录不存在问题也不会成为罪魁祸首。