|
刚做过这样的一个应用,趁着现在还比较熟悉。粘上来供大家学习之用,也便于自己以后时常可以参考。
在这部分的操作中,需要三个外部的应用:exe4j_ejtechnologies.exe,instsrv.exe,srvany.exe。
首先将自己做好的java项目即jar包通过exe4j_ejtechnologies.exe打包成exe格式的文件。在指定目录里面创建文件夹将打包好的exe文件存放在指定目录中,并且同时在目录里面创建./ToServer文件夹(后面用到)。将instsrv.exe,srvany.exe两个文件存放在./ToServer中.
public class Buildfile {
String instsrv = "\\ToServer\\instsrv.exe"; String srvany = "\\ToServer\\srvany.exe"; public List getRegContent(String fileName,String serverName){ File file = new File(fileName); String path = ""; String root = ""; File temp1 = null; File temp2 = null; List list = new ArrayList<String>(); if(file.exists()){ path = file.getAbsolutePath(); root = path.substring(0, path.lastIndexOf("\\")); if(root.endsWith(File.separator)){ temp1 = new File(root+instsrv); temp2 = new File(root+srvany); }else{ temp1 = new File(root+File.separator+instsrv); temp2 = new File(root+File.separator+srvany); } list.add(0, "@echo off"); list.add(1, "rem as follows is regedit system server"); list.add(2, temp1.getAbsolutePath()+" "+serverName+" "+temp2.getAbsolutePath()); list.add(3, "rem as follows is regedit key assignments"); list.add(4, "start REG ADD HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\"+serverName+"\\Parameters /v Application /t REG_SZ /d "+path); } return list; } public String getRemContent(String fileName,String serverName){ File file = new File(fileName); String path = ""; String root = ""; File temp1 = null; if(file.exists()){ path = file.getAbsolutePath(); root = path.substring(0, path.lastIndexOf("\\")); if(root.endsWith(File.separator)){ temp1 = new File(root+instsrv); }else{ temp1 = new File(root+File.separator+instsrv); } } String str = temp1.toString()+" "+serverName+" "+"remove"; return str; } public static void writeLog(String filePath,String content){ FileWriter tofile; BufferedWriter bfw; try { tofile = new FileWriter(filePath, true); bfw = new BufferedWriter(tofile); bfw.write(content, 0, content.length()); bfw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { Buildfile test = new Buildfile(); File file1 = new File("regeditServer.bat"); File file2 = new File("UninsServer.bat"); if(file1.exists()&&file2.exists()){ System.exit(0); }else{ for(int i=0;i<test.getRegContent("ServerConsole.exe","ServerApp").size();i++){ String str = (String) test.getRegContent("ServerConsole.exe","ServerApp").get(i); writeLog("regeditServer.bat", str+"\n"); } writeLog("UninsServer.bat", test.getRemContent("ServerConsole.exe","ServerApp")+"\n"); } } }
将上面的类做成一个项目,并且打包。在上面的类中特别注意的是在main()方法里面的参数,例如ServerConsole.exe为自己做的exe文件的名字,ServerApp为需要打包的服务名字。
将打包好的项目存放在自己exe文件的当前目录,些一个批处理来执行jar包,生成两个新文件分别为:regeditServer.bat和UninsServer.bat。通过点击regeditServer.bat就可以将exe注册成服务,点击UninsServer.bat便可以移除此系统服务的。
|