如何将jar文件移动到StartUp文件夹-Java

时间:2018-06-24 13:04:45

标签: java file

我尝试使用以下代码将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却没有移动,为什么?

1 个答案:

答案 0 :(得分:0)

根据Java documentation for File class

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)(请参阅documentation)来移动文件,该文件与平台无关。 / li>