首页 > 解决方案 > 如何将 jar 文件移动到 StartUp 文件夹 - Java

问题描述

我尝试 text and jar file使用以下代码移动到 StartUp 文件夹:

File m = new File("C:\\Users\\danyb\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\lol.txt");//startup the text file
    File m2 = new File("Arma3.jar");//where the first file
    File m3 = new  File("C:\\Users\\danyb\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\Arma3.jar");//startup the jar file

    if( !m.exists()&& !m3.exists()){
        m.createNewFile();
        System.out.println("a");
        m2.renameTo(m3);
        System.out.println("a");
        FileWriter fr = new FileWriter("C:\\Users\\danyb\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\lol.txt");
        BufferedWriter br = new BufferedWriter(fr);
        br.write("lol");
        br.close();




       return;


    }

我们对此进行了测试,结果是:“lol.txt”文件已创建,但 Arma3.jar 文件没有移动到文件夹,但m2.renameTo(m3);执行后的代码但 Arma3.jar 没有移动 为什么?

标签: javafile

解决方案


根据File 类的 Java 文档

public boolean renameTo(File dest)
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

Note that the Files class defines the move method to move or rename a file in a platform independent manner.

换句话说:

  1. 方法File.renameTo(File)可能会失败并返回 false - 您应该始终检查它并通过例如抛出异常或重试操作来处理这种情况。确定实际出错的唯一方法是使用调试器,但即便如此,您最终也可能会遇到调试器无法进入的本机方法。
  2. 方法File.renameTo(File)依赖于平台,这意味着它在不同操作系统上的工作方式不同。由于使用 Java 的全部意义在于生成能够在多个系统上正确运行的应用程序,因此最好使用与平台无关的Files.move(Path, Path, CopyOptions)(参见文档)来移动文件。

推荐阅读