Java move application to startup folder

2.1k views Asked by At

I am trying to add my APP 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;
    }
    
}

That's the class I store info methods

And the main class:

    System.out.println(info.getautostart() + "\\asdf.jar");
    System.out.println(info.getrunningdir());
    Files.move(info.getrunningdir(), info.getautostart() + "\\asdf.jar");

This is the output from println:

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

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

The files.move is not working.

2

There are 2 answers

0
GameDroids On BEST ANSWER

OK lets say you want to move your jar from the current directory to the autostart folder. You already have these methods:

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

Now moving a file needs Paths and not String so you need to create a Path instance for each of your Strings:

 Path autostartPath = Paths.get(getautostart());
 Path currentPath = Paths.get(getrunningdir());

If you want to point to a file (like your .jar file) within the paths you can do this:

currentPath.resolve("myProgram.jar"); // The paths end with a `/` so you don't need to add it here

All together the move should look like this:

Files.move(currentPath.resolve("myProgram.jar"), autostartPath.resolve("myProgram.jar"));
1
Hummeling Engineering BV On

You should use File and Path objects instead of String objects (Path in Files.move()).

Path is made for adding 'parts' and you can check directory existence easily.

BTW, is the file you're moving, asdf.jar, also the file you're running? The JVM prevents running jars from being deleted or moved.