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

Java move application to startup folder

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

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

这就是class我存储信息的方法

和主要 class:

    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

files.move 不工作。

您应该使用 FilePath 对象而不是 String 对象(Files.move() 中的 Path)。

Path是为了添加'parts'而创建的,您可以轻松检查目录是否存在。

顺便说一句,您要移动的文件是 asdf.jar,也是您要移动的文件 运行? JVM 防止删除或移动 运行 个 jar。

好的,假设您想将 jar 从当前目录移动到自动启动文件夹。您已经拥有这些方法:

// 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;
}

现在移动文件需要 Paths 而不是 String 因此您需要为每个字符串创建一个 Path 实例:

 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

总的来说 move 应该是这样的:

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