1

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

Kaan
  • 5,434
  • 3
  • 19
  • 41
Hajex
  • 13
  • 2
  • If you are getting "access denied", there is not much you can do about it in Java. This implies that the application needs to be run with administrator privilege (or something like that). Only the user can do that. An application cannot escalate its privilege. That would render the access control meaningless ... from a security perspective. – Stephen C Jul 09 '22 at 09:25
  • @StephenC but there must be a way to realize a Autostart option in a Java Programm right? – Hajex Jul 09 '22 at 09:26
  • Only if the Java program is run >by the user< with administrator privilege. – Stephen C Jul 09 '22 at 09:26
  • i dont find an option by rightclicking the .jar to start it with Administrator-right and i also tried Starting the Programm from a cmd-prompt wich i started with Administrator Rights and it throw me the same error – Hajex Jul 09 '22 at 09:30
  • 1
    Alternatively; see https://stackoverflow.com/questions/1385866 which explains how to get Java to run some other program with admin privilege. Note that `elevate.exe` will prompt the user for permission. – Stephen C Jul 09 '22 at 09:30

1 Answers1

0

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"
Rob Spoor
  • 6,186
  • 1
  • 19
  • 20