I would like to run my Java program on System Startup on Mac OS/Windows. How can I do this?

Posted by Misha Koshelev on Stack Overflow See other posts from Stack Overflow or by Misha Koshelev
Published on 2010-06-01T12:18:18Z Indexed on 2010/06/01 12:23 UTC
Read the original article Hit count: 181

Filed under:
|
|
|

Here is what I came up with. It works but I was wondering if there is something more elegant. Thank you!

Misha

package com.mksoft.fbbday;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

public class RunOnStartup {
    public static void install(String className,boolean doInstall) throws IOException,URISyntaxException {
 String osName=System.getProperty("os.name");
 String fileSeparator=System.getProperty("file.separator");
 String javaHome=System.getProperty("java.home");
 String userHome=System.getProperty("user.home");
 File jarFile=new File(RunOnStartup.class.getProtectionDomain().getCodeSource().getLocation().toURI());

 if (osName.startsWith("Windows")) {
     Process process=Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v Startup");
     BufferedReader in=new BufferedReader(new InputStreamReader(process.getInputStream()));
     String result="",line;
     while ((line=in.readLine())!=null) {
  result+=line;
     }
     in.close();
     result=result.replaceAll(".*REG_SZ[ ]*","");

     File startupFile=new File(result+fileSeparator+jarFile.getName().replaceFirst(".jar",".bat"));
     if (doInstall) {
  PrintWriter out=new PrintWriter(new FileWriter(startupFile));
  out.println("@echo off");
  out.println("start /min \"\" \""+javaHome+fileSeparator+"bin"+fileSeparator+"java.exe -cp "+jarFile+" "+className+"\"");
  out.close();
     } else {
  if (startupFile.exists()) {
      startupFile.delete();
  }
     }
 } else if (osName.startsWith("Mac OS")) {
     File startupFile=new File(userHome+"/Library/LaunchAgents/com.mksoft."+jarFile.getName().replaceFirst(".jar",".plist"));
     if (doInstall) {
  PrintWriter out=new PrintWriter(new FileWriter(startupFile));
  out.println("");
  out.println("");
  out.println("");
  out.println("");
  out.println("   Label");
  out.println("   com.mksoft."+jarFile.getName().replaceFirst(".jar","")+"");
  out.println("   ProgramArguments");
  out.println("   ");
  out.println("      "+javaHome+fileSeparator+"bin"+fileSeparator+"java");
  out.println("      -cp");
  out.println("      "+jarFile+"");
  out.println("      "+className+"");
  out.println("   ");
  out.println("   RunAtLoad");
  out.println("   ");
  out.println("");
  out.println("");
  out.close();
     } else {
  if (startupFile.exists()) {
      startupFile.delete();
  }
     }
 }
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about Windows