我想在Mac OS/Windows系统启动时运行Java程序。我该怎么做?
这是我想到的。它可以工作,但我想知道是否有更优雅的东西。谢谢大家! 米沙我想在Mac OS/Windows系统启动时运行Java程序。我该怎么做?,java,windows,macos,startup,Java,Windows,Macos,Startup,这是我想到的。它可以工作,但我想知道是否有更优雅的东西。谢谢大家! 米沙 /*版权所有(c)2010米沙·科舍列夫。版权所有。 * *待办事项: *-添加Linux支持 */ 包com.mksoft.common; 导入java.io.BufferedReader; 导入java.io.File; 导入java.io.FileWriter; 导入java.io.InputStreamReader; 导入java.io.IOException; 导入java.io.PrintWriter; 导入j
/*版权所有(c)2010米沙·科舍列夫。版权所有。
*
*待办事项:
*-添加Linux支持
*/
包com.mksoft.common;
导入java.io.BufferedReader;
导入java.io.File;
导入java.io.FileWriter;
导入java.io.InputStreamReader;
导入java.io.IOException;
导入java.io.PrintWriter;
导入java.net.URI;
导入java.net.URISyntaxException;
/**
*在系统启动时在此JAR文件中运行指定的类。
*
*@作者米莎·科舍列夫
*/
公共类runnsystemstartup{
/*
*常数
*/
受保护的最终静态字符串osName=System.getProperty(“os.name”);
受保护的最终静态字符串fileSeparator=System.getProperty(“file.separator”);
受保护的最终静态字符串javaHome=System.getProperty(“java.home”);
受保护的最终静态字符串userHome=System.getProperty(“user.home”);
/*
*调试
*/
受保护的静态布尔调试输出=false;
受保护的静态无效调试(字符串消息){
如果(调试输出){
System.err.println(消息);
System.err.flush();
}
}
/*
*助手
*/
受保护的静态文件getJarFile()引发URI语法异常{
返回新文件(RunOnSystemStartup.class.getProtectionDomain().getCodeSource().getLocation().Tori());
}
受保护的静态文件getStartupFile()引发异常{
调试(“runnsystemstartup.getStartupFile:osName=\”“+osName+\”);
if(osName.startsWith(“Windows”)){
Process Process=Runtime.getRuntime().exec(“reg query\”HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\“/v Startup”);
BufferedReader in=新的BufferedReader(新的InputStreamReader(process.getInputStream());
字符串结果=”,行;
而((line=in.readLine())!=null){
结果+=行;
}
in.close();
result=result.replaceAll(“.*REG_SZ[]*”,”);
调试(“runnsystemstartup.getStartupFile:Startup Directory=\”“+result+\”);
返回新文件(result+fileSeparator+getJarFile().getName().replaceFirst(“.jar”,“.bat”));
}else if(osName.startsWith(“Mac OS”)){
返回新文件(userHome+“/Library/LaunchAgents/com.mksoft.”+getJarFile().getName().replaceFirst(“.jar”,“.plist”);
}否则{
抛出新异常(“未知操作系统名称\”+osName+“\”);
}
}
/*
*方法
*/
/**
*返回是否安装此JAR文件以在系统启动时运行。
*/
公共静态布尔值isInstalled()引发异常{
返回getStartupFile().exists();
}
/**
*从当前JAR文件安装指定的类以在系统启动时运行。
*
*@param className当前JAR文件中要在系统启动时运行的类的名称。
*@param windowTitle显示在窗口标题栏中(如果适用)。
*/
公共静态void安装(字符串className,字符串windowTitle)引发异常{
File startupFile=getStartupFile();
PrintWriter out=新的PrintWriter(新的FileWriter(startupFile));
if(osName.startsWith(“Windows”)){
out.println(“@echo off”);
out.println(“start\”“+windowTitle+”\“\”“+javaHome+fileSeparator+“bin”+fileSeparator+“java.exe\”-cp”+getJarFile()+”“+className);
}else if(osName.startsWith(“Mac OS”)){
out.println(“”);
out.println(“”);
out.println(“”);
out.println(“”);
out.println(“标签”);
out.println(“com.mksoft.+getJarFile().getName().replaceFirst”(.jar),“)+”;
out.println(“程序参数”);
out.println(“”);
println(“+javaHome+fileSeparator+bin+fileSeparator+java”);
out.println(“-cp”);
out.println(“+getJarFile()+”);
out.println(“+className+”);
out.println(“”);
out.println(“RunAtLoad”);
out.println(“”);
out.println(“”);
out.println(“”);
}否则{
抛出新异常(“未知操作系统名称\”+osName+“\”);
}
out.close();
}
/**
*从系统启动过程中卸载此JAR文件。
*/
public static void uninstall()引发异常{
File startupFile=getStartupFile();
if(startupFile.exists()){
删除();
}
}
}
如果您在“开始”菜单的“启动”文件夹中创建快捷方式(针对当前用户或所有用户,具体取决于您希望它运行的时间),Windows将在启动时为您运行它。它是服务还是用户应用程序?如果有一项服务需要查看。感谢您提供了这个宝石,我在最近的开发中使用了它
我在方法中使用的唯一改进是plist的构造。我在包中包含了一个模板XML。然后我使用一个类加载器读入XML,然后像上面那样使用一个文件来编写
(少一点改进,多一点整理,见下文)
再次感谢您对原始帖子的帮助。喜欢您编写代码的方式
/* Copyright (c) 2010 Misha Koshelev. All Rights Reserved.
*
* TODO:
* - Add Linux support
*/
package com.mksoft.common;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Run specified class within this JAR file on system startup.
*
* @author Misha Koshelev
*/
public class RunOnSystemStartup {
/*
* Constants
*/
protected final static String osName=System.getProperty("os.name");
protected final static String fileSeparator=System.getProperty("file.separator");
protected final static String javaHome=System.getProperty("java.home");
protected final static String userHome=System.getProperty("user.home");
/*
* Debugging
*/
protected static boolean debugOutput=false;
protected static void debug(String message) {
if (debugOutput) {
System.err.println(message);
System.err.flush();
}
}
/*
* Helpers
*/
protected static File getJarFile() throws URISyntaxException {
return new File(RunOnSystemStartup.class.getProtectionDomain().getCodeSource().getLocation().toURI());
}
protected static File getStartupFile() throws Exception {
debug("RunOnSystemStartup.getStartupFile: osName=\""+osName+"\"");
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[ ]*","");
debug("RunOnSystemStartup.getStartupFile: Startup Directory=\""+result+"\"");
return new File(result+fileSeparator+getJarFile().getName().replaceFirst(".jar",".bat"));
} else if (osName.startsWith("Mac OS")) {
return new File(userHome+"/Library/LaunchAgents/com.mksoft."+getJarFile().getName().replaceFirst(".jar",".plist"));
} else {
throw new Exception("Unknown Operating System Name \""+osName+"\"");
}
}
/*
* Methods
*/
/**
* Returns whether this JAR file is installed to run on system startup.
*/
public static boolean isInstalled() throws Exception {
return getStartupFile().exists();
}
/**
* Install the specified class from the current JAR file to run on system startup.
*
* @param className Name of class within the current JAR file to run on system startup.
* @param windowTitle Title to display in window title bar, if applicable.
*/
public static void install(String className,String windowTitle) throws Exception {
File startupFile=getStartupFile();
PrintWriter out=new PrintWriter(new FileWriter(startupFile));
if (osName.startsWith("Windows")) {
out.println("@echo off");
out.println("start \""+windowTitle+"\" \""+javaHome+fileSeparator+"bin"+fileSeparator+"java.exe\" -cp "+getJarFile()+" "+className);
} else if (osName.startsWith("Mac OS")) {
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.println("<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">");
out.println("<plist version=\"1.0\">");
out.println("<dict>");
out.println(" <key>Label</key>");
out.println(" <string>com.mksoft."+getJarFile().getName().replaceFirst(".jar","")+"</string>");
out.println(" <key>ProgramArguments</key>");
out.println(" <array>");
out.println(" <string>"+javaHome+fileSeparator+"bin"+fileSeparator+"java</string>");
out.println(" <string>-cp</string>");
out.println(" <string>"+getJarFile()+"</string>");
out.println(" <string>"+className+"</string>");
out.println(" </array>");
out.println(" <key>RunAtLoad</key>");
out.println(" <true/>");
out.println("</dict>");
out.println("</plist>");
} else {
throw new Exception("Unknown Operating System Name \""+osName+"\"");
}
out.close();
}
/**
* Uninstall this JAR file from the system startup process.
*/
public static void uninstall() throws Exception {
File startupFile=getStartupFile();
if (startupFile.exists()) {
startupFile.delete();
}
}
}
private String loadPlistXML() {
StringBuilder file = new StringBuilder();
try{
is = this.getClass().getClassLoader().getResourceAsStream("LaunchPList.xml");
logger.info("is = " + (is != null));
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line = in.readLine()) != null) {
file.append(line +"\n");
}
}catch(Error e){
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file.toString();
}