Java将应用程序移动到启动文件夹

Java将应用程序移动到启动文件夹,java,move,startup,autostart,Java,Move,Startup,Autostart,我正在尝试将我的应用程序添加到启动文件夹 public class info { public static String getautostart() { return System.getProperty("java.io.tmpdir").replace("Local\\Temp\\", "Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup&

我正在尝试将我的应用程序添加到启动文件夹

public class info {
    
    public static String getautostart() {
        return System.getProperty("java.io.tmpdir").replace("Local\\Temp\\", "Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup");
    }
    
    public static String gettemp() {
        String property = "java.io.tmpdir";
        String tempDir = System.getProperty(property);
        return tempDir;
    }
    
    public static String getrunningdir() {
        String runningdir = ProjectGav.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        return runningdir;
    }
    
}
这是类I存储信息方法

主要课程包括:

    System.out.println(info.getautostart() + "\\asdf.jar");
    System.out.println(info.getrunningdir());
    Files.move(info.getrunningdir(), info.getautostart() + "\\asdf.jar");
这是println的输出:

C:\Users\JOHNDO~1\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\asdf.jar

/C:/Users/John%20Doe/Downloads/project1.jar


文件.move
不起作用。

您应该使用
文件
路径
对象,而不是
字符串
对象(
文件.move()中的
路径

路径
用于添加“部件”,您可以轻松检查目录是否存在


顺便问一下,您正在移动的文件,
asdf.jar
,也是您正在运行的文件吗?JVM防止删除或移动正在运行的jar。

好,假设您想将jar从当前目录移动到autostart文件夹。您已经有了以下方法:

// nothing to change here - it seems to work just fine
public static String getautostart() {
    return System.getProperty("java.io.tmpdir").replace("Local\\Temp\\", "Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup");
}

// this one got confused with the '/' and '\' so I changed it
public static String getrunningdir() {
     //you need to import java.nio.file.Paths for that.
    String runningdir = Paths.get(".").toAbsolutePath().normalize().toString(); // it simulates the creation of a file in the current directory and returns the path for that file
    return runningdir;
}
现在移动文件需要
路径
,而不是
字符串
,因此需要为每个字符串创建路径实例:

 Path autostartPath = Paths.get(getautostart());
 Path currentPath = Paths.get(getrunningdir());
如果要指向路径中的文件(如
.jar
文件),可以执行以下操作:

currentPath.resolve("myProgram.jar"); // The paths end with a `/` so you don't need to add it here
总之,
移动
应该如下所示:

Files.move(currentPath.resolve("myProgram.jar"), autostartPath.resolve("myProgram.jar"));

如果我没有弄错的话,您需要在windows启动文件夹中创建一个快捷方式,而不是复制整个jar。也许我能帮你。我的第一个想法是:在
.jar
文件旁边创建一个
.vbs
文件(使用链接中的脚本)。然后从您的java应用程序中。我想移动文件,而不是创建一个快捷点!也许
文件。复制(从、到)
在这里是更明智的选择