Home > OS >  Copy a File into the Startup folder with Java
Copy a File into the Startup folder with Java

Time:07-10

I want to code a program in which the user can turn on "Autostart", that means that the Program will automatically start when the Windows 10 PC Starts.

Doing it manually is simple, I can put a shortcut or the .jar File in the Windows Startup folder, but when I try to make this toggleable from my program, I get a problem.

public void run() {
        File src = new File("Test.txt"); //my test File
        File dst = new File("C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\itWorked.txt"); //StartUp Folder
        
        try {
            Files.copy(src.toPath(),dst.toPath() , StandardCopyOption.REPLACE_EXISTING); //Copy
        } catch (IOException e) {e.printStackTrace();}
    }

This is my code to copy files, if I copy my "Test.txt" to my Desktop, it works but when I try to copy this into the Startup Folder, it throws me a <java.nio.file.AccessDeniedException>

I also tried starting my program from cmd with Administrator-rights but it didn't work either.

How can I copy a File into the Startup Folder from Windows to let my program automatically run after a PC restart using Java Code?

PS: it only have to work on Windows 10

CodePudding user response:

Use the following instead, to use the user's own startup folder. It would need to be done per user though.

System.getProperty("user.home")   "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"

Probably better, because it also works if the user changed where the roaming data is stored:

System.getenv("APPDATA")   "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
  • Related