Created
August 31, 2014 06:58
-
-
Save anonymous/ced7d2e0c8f2d2d3f47a to your computer and use it in GitHub Desktop.
Java: Add Jar File to Windows Startup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dany.test3; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.PrintWriter; | |
import java.net.URI; | |
import java.net.URISyntaxException; | |
import sun.awt.OSInfo; | |
import sun.awt.OSInfo.OSType; | |
public class Test31 | |
{ | |
public static final String programName = "MyProgram"; | |
public static void main(String[] args) throws Throwable | |
{ | |
if (args[0].equals("-ADD")) | |
{ | |
// Catch IOException | |
addToStartup("-DELETE", false); | |
} | |
else if (args[0].equals("-DELETE")) | |
{ | |
// Catch IOException and URISyntaxException | |
addToStartup(null, true); | |
} | |
} | |
/** | |
* Add a jar file to windows startup | |
* @param jarFile Jar File | |
* @param args Arguments line | |
* @param delete <code>true</code> to delete it from startup if exists, <code>false</code> to add | |
* @throws IOException Reading/writing failed, maybe not enough rights | |
*/ | |
public static void addToStartup(File jarFile, String args, boolean delete) throws IOException | |
{ | |
if (OSInfo.getOSType() == OSType.WINDOWS) | |
{ | |
File startupFolder = new File(System.getenv("APPDATA") + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"); | |
File batch = new File(startupFolder, programName + ".bat"); | |
if (delete) | |
{ | |
// Removing from startup... | |
if (batch.exists()) | |
{ | |
batch.delete(); | |
} | |
// Removing from startup finished | |
} | |
else | |
{ | |
// Adding to startup... | |
if (!batch.exists()) | |
{ | |
batch.createNewFile(); | |
} | |
PrintWriter bw = new PrintWriter(batch); | |
bw.println("javaw -jar \"" + jarFile.getPath() + "\" " + args); | |
bw.close(); | |
// Adding to startup finished | |
} | |
} | |
else | |
{ | |
// Unsupported OS | |
} | |
} | |
/** | |
* Add a current jar file to windows startup | |
* @param args Arguments line | |
* @param delete <code>true</code> to delete it from startup if exists, <code>false</code> to add | |
* @throws IOException Reading/writing failed, maybe not enough rights | |
* @throws URISyntaxException Failed to get current jar file URI | |
*/ | |
public static void addToStartup(String args, boolean delete) throws IOException, URISyntaxException | |
{ | |
URI jar = Test31.class.getProtectionDomain().getCodeSource().getLocation().toURI(); | |
addToStartup(new File(jar), args, delete); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment