簡體   English   中英

Java將應用程序移動到啟動文件夾

[英]Java move application to startup folder

我正在嘗試將我的 APP 添加到啟動文件夾。

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

那是我存儲信息方法的類

和主類:

    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用於添加“部分”,您可以輕松檢查目錄是否存在。

順便說一句,您正在移動的文件asdf.jar也是您正在運行的文件嗎? JVM 可防止刪除或移動正在運行的 jar。

OK 假設您想將 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"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM