首页 > 编程知识 正文

使用java启动windows(使用java启动和停止一个本地程序)

时间:2023-12-05 14:04:53 阅读:312287 作者:JPFM

本文目录一览:

  • 1、如何注册java程序为windows服务
  • 2、如何写一个Java程序自动启动一个windows系统服务?或者关闭、重启?
  • 3、java启动windows命令行
  • 4、windows怎么运行java程序
  • 5、如何用java启动windows命令行程序

如何注册java程序为windows服务

这里介绍下如何利用javaService 软件把java 程序注册为windows 服务。

一、 利用javaService 注册java 程序为windows 服务

[1] 下载javaService

访问网址 下载windows 版本的javaService 文件,我下载的是JavaService-2.0.10.rar ,目前最新的版本就是“2.0.10 ”。

[2] 安装javaService

解压我们下载下来的javaServices 到一个目录,我是解压到目录“D:/software/JavaService-2.0.10 ”下(解压到任何目录都可以,最好别解压到中文目录,省的出现问题 )

[3] 编写定时关机代码,见第二章的定时关机代码

1) 具体代码参加第二章,类的名字为:

com.test.timer.TimerShutDownWindows

2) 把编写后的java 文件导出为class 的形式,把导出的类放到目录“D:/software/JavaService-2.0.10/classes/com/test/timer ”下。也就是把导出的com 包放到

“D:/software/JavaService-2.0.10/classes” 目录下。

[4] 注册java 程序为windows 服务

进入“D:/software/JavaService-2.0.10 “目录,执行如下命令:

JavaService.exe -install MyShutDownService "%JAVA_HOME%"/jre/bin/server/jvm.dll -Djava.class.path="%JAVA_HOME%"/lib/tools.jar;D:/software/JavaService-2.0.10/classes -start com.test.timer.TimerShutDownWindows

其中“-install “后面的参数为服务的名称,“-start ”参数后边是要启动的类名,“Djava.class.path ”后面参数中的

“D:/software/JavaService-2.0.10/classe ”地址是我的“TimerShutDownWindows ”类存放的路径,实际应用中修改为自己的classPath 即可。

这里需要注意几点:

1) “%JAVA_HOME% ”jdk 目录,如果没有配置jdk 目录,则替换为jdk 的实际绝对地址。

2) -Djava.class.path 是必须的,因为服务启动的时候无法访问系统的CLASSPATH 变量,所以必须在这里声明;如果jar 比较多,为避免写的命令过长,我们可以使用“-Djava.ext.dirs=jars 所在目录”参数。

3) 服务添加之后,可以在命令行中敲入“services.msc ”命令来查看所有服务,并可以对服务的启动类型(自动启动还是手动启动等)进行修改。

[5] 测试

1) 启动服务

当我们注册完服务后,我们可以通过命令“net start MyShutDownService ”来启动该服务,服务启动后会在D 盘根目录生成my_shutdown.log 日志文件。

2) 关闭服务

如果我们要关闭服务,可以通过命令“net stop MyShutDownService ”来关闭该服务。

3) 删除服务

当我们想删除该服务时,可以使用命令“sc delete MyShutDownService ”来删除该服务。

二、 定时关机代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

package com.test.timer;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

public class TimerShutDownWindows {

/* 检测是否需要关机的时间间隔 */

private static long m_nDetectInterval = 5000;

/* 记录上次检测的时间,以毫秒为单位 */

private static long m_lLastMilliSeconds = 0;

/* 可以使用电脑的最小小时 */

private static int m_nUsePCMinHour = 17;

/* 可以使用电脑的最大小时 */

private static int m_nUseComputerMaxHour = 23;

/* 如果分钟超过这个时间,则关机计算机 */

private static int m_nMinutes = 25;

/* 记录日志的文件的保存位置 */

private static String m_sLogFile = "D:" + File.separator

+ "my_shutdown.log";

/* 记录当前系统是否已经启动自动关闭程序 */

private static boolean bHasShutDownPC = false;

/**

* @param args

*/

public static void main(String[] args) {

// 1. 单独开启一个线程去检测

Thread aThread = new Thread(new TimerDetector());

aThread.start();

}

/**

* 定义内部类

*

* @author Administrator

*

*/

static class TimerDetector implements Runnable {

/*

* (non-Javadoc)

*

* @see java.lang.Runnable#run()

*/

public void run() {

// 1. 获取日志文件

PrintWriter out = null;

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try {

out = new PrintWriter(new FileWriter(m_sLogFile, true), true);

} catch (IOException e1) {

out = null;

e1.printStackTrace();

}

// 2. 记录服务启动时间

appendLog(out, " 服务启动时间:" + df.format(new Date()));

while (true) {

// 1. 判断当前系统时间是否被修改过

boolean bShoudShutDownPC = validateShoudShutDownPC(out);

if (bShoudShutDownPC) {

// 验证没通过,强制关机

exectueShutDown(out);

} else {

bHasShutDownPC = false;

}

// 2. 当前线程休眠下

try {

Thread.sleep(m_nDetectInterval);

} catch (InterruptedException e) {

appendLog(out, e.getMessage());

}

}

}

/**

* 验证当前时间是否是需要关机的时间

*

* @return

*/

private boolean validateShoudShutDownPC(PrintWriter _out) {

// 1. 判断是否修改了系统时间

boolean bHasModifySystemTime = detectModifySytemTime(_out);

appendLog(_out, "bHasModifySystemTime :" + bHasModifySystemTime);

if (bHasModifySystemTime) {

return bHasModifySystemTime;

}

// 2. 没有修改系统时间,则判断当前时间是否超过了指定的时间

boolean bShoudSleep = nowIsSleepTime();

appendLog(_out, "bShoudSleep :" + bShoudSleep);

if (bShoudSleep) {

return bShoudSleep;

}

return false;

}

/**

* 判断当前时间是否应该休息的时间

*

* @return

*/

private boolean nowIsSleepTime() {

// 1. 获取当前小时和分钟

Calendar aCalendar = Calendar.getInstance();

int nHour = aCalendar.get(Calendar.HOUR_OF_DAY);

int nMinute = aCalendar.get(Calendar.MINUTE);

// 2. 判断当前小时是否在可以使用PC 的时间内, 最大小时为23

if (nHour m_nUsePCMinHour) {

return true;

}

// 23 点需要单独判断,超过23 点30 就应该休息

if ((nHour = m_nUseComputerMaxHour) (nMinute = m_nMinutes)) {

return true;

}

// 3. 非休息时间

return false;

}

/**

* 判断是否有人修改了系统时间,如果有人修改了系统时间返回true ,

* 否则返回false

*

* @return

*/

private boolean detectModifySytemTime(PrintWriter _out) {

// 1. 第一次检测系统时间

if (m_lLastMilliSeconds == 0) {

m_lLastMilliSeconds = System.currentTimeMillis();

return false;

}

// 2. 检测两次时间的差值

long lInteral = System.currentTimeMillis() - m_lLastMilliSeconds;

lInteral = Math.abs(lInteral);

// 3. 判断两次的时间间隔, 两次结果不一定完全等于 m_nDetectInterval ,允许误差为1 分钟

long lMaxInterval = m_nDetectInterval + 60 * 1000;

appendLog(_out, "lInteral :::" + lInteral);

appendLog(_out, "lMaxInterval :::" + lMaxInterval);

if (lInteral lMaxInterval) {

// 有人修改了系统时间,强制关机

return true;

}

// 4. 只有没人修改时间才记录上次检测时间

m_lLastMilliSeconds = System.currentTimeMillis();

return false;

}

/**

* 在指定的流中写入日志信息

*

* @param _outWriter

* @param _sAppendContent

*/

private void appendLog(PrintWriter _outWriter, String _sAppendContent) {

if (_outWriter == null) {

return;

}

_outWriter.println(_sAppendContent);

}

/**

* 执行关机命令

*/

private void exectueShutDown(PrintWriter _out) {

if (bHasShutDownPC) {

SimpleDateFormat df = new SimpleDateFormat(

"yyyy-MM-dd HH:mm:ss");

appendLog(_out, " 系统即将关闭, 当前时间:" + df.format(new Date()));

return;

}

appendLog(_out, " 有人修改了系统时间,系统强制关机!");

// 关机

try {

Runtime.getRuntime().exec(

"shutdown -s -t 120 -c /" 很晚了,该睡觉了,2 分钟后关闭计算机。/"");

} catch (IOException e) {

appendLog(_out, e.getMessage());

}

bHasShutDownPC = true;

}

}

}

如何写一个Java程序自动启动一个windows系统服务?或者关闭、重启?

dos 的 net start 命令就可以了。你可以写一个bat,也可以在cmd命令下执行

比如:net start oracleserviceorcl

java启动windows命令行

这是摘自JAVA NB 网 上的例子。

如何用java启动windows命令行程序:

先请编译和运行下面程序:

import java.util.*;

import java.io.*;

public class BadExecJavac2

{

public static void main(String args[])

{

try

{

Runtime rt = Runtime.getRuntime();

Process proc = rt.exec("javac");

int exitVal = proc.waitFor();

System.out.println("Process exitValue: " + exitVal);

} catch (Throwable t){

t.printStackTrace();

}

}

}

我们知道javac命令,当不带参数运行javac 程序时,它将输出帮助说明,为什么上面程序不产生任何输出并挂起,永不完成呢?java文档上说,由于有些本地平台为标准输入和输出流所提供的缓冲区大小有限,如果不能及时写入子进程的输入流或者读取子进程的输出流,可能导致子进程阻塞,甚至陷入死锁。所以,上面的程序应改写为:

import java.util.*;

import java.io.*;

public class MediocreExecJavac

{

public static void main(String args[])

{

try

{

Runtime rt = Runtime.getRuntime();

Process proc = rt.exec("javac");

InputStream stderr = proc.getErrorStream();

InputStreamReader isr = new InputStreamReader(stderr);

BufferedReader br = new BufferedReader(isr);

String line = null;

System.out.println("");

while ( (line = br.readLine()) != null)

System.out.println(line);

System.out.println("");

int exitVal = proc.waitFor();

System.out.println("Process exitValue: " + exitVal);

} catch (Throwable t){

t.printStackTrace();

}

}

}

下面是正确的输出:

D:javajava MediocreExecJavac

Usage: javac 〈OPTIONs

where possible options include:

-g Generate all debugging info

-g:none Generate no debugging info

-g:{lines,vars,source} Generate only some debugging info

-nowarn Generate no warnings

-verbose Output messages about what the compiler is doing

-deprecation Output source locations where deprecated APIs are used

-classpath Specify where to find user class files

-cp Specify where to find user class files

-sourcepath Specify where to find input source files

-bootclasspath Override location of bootstrap class files

-extdirs Override location of installed extensions

-endorseddirs Override location of endorsed standards path

-d Specify where to place generated class files

-encoding Specify character encoding used by source files

-source Provide source compatibility with specified release

-target Generate class files for specific VM version

-version Version information

-help Print a synopsis of standard options

-X Print a synopsis of nonstandard options

-J Pass directly to the runtime system

Process exitValue: 2

D:java

下面是一个更一般的程序,它用两个线程同步清空标准错误流和标准输出流,并能根据你所使用的windows操作系统选择windows命令解释器command.com或cmd.exe,然后执行你提供的命令。

import java.util.*;

import java.io.*;

class StreamGobbler extends Thread

{

InputStream is;

String type; //输出流的类型ERROR或OUTPUT

StreamGobbler(InputStream is, String type)

{

this.is = is;

this.type = type;

}

public void run()

{

try

{

InputStreamReader isr = new InputStreamReader(is);

BufferedReader br = new BufferedReader(isr);

String line=null;

while ( (line = br.readLine()) != null)

{

System.out.println(type + "" + line);

System.out.flush();

}

} catch (IOException ioe)

{

ioe.printStackTrace();

}

}

}

public class GoodWindowsExec

{

public static void main(String args[])

{

if (args.length 1)

{

System.out.println("USAGE: java GoodWindowsExec ");

System.exit(1);

}

try

{

String osName = System.getProperty("os.name" );

System.out.println("osName: " + osName);

String[] cmd = new String[3];

if(osName.equals("Windows XP") ||osName.equals("Windows 2000"))

{

cmd[0] = "cmd.exe" ;

cmd[1] = "/C" ;

cmd[2] = args[0];

}

else if( osName.equals( "Windows 98" ) )

{

cmd[0] = "command.com" ;

cmd[1] = "/C" ;

cmd[2] = args[0];

}

Runtime rt = Runtime.getRuntime();

System.out.println("Execing " + cmd[0] + " " + cmd[1]+ " " + cmd[2]);

Process proc = rt.exec(cmd);

// any error message?

StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

// any output?

StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

// kick them off

errorGobbler.start();

outputGobbler.start();

// any error???

int exitVal = proc.waitFor();

System.out.println("ExitValue: " + exitVal);

} catch (Throwable t){

t.printStackTrace();

}

}

}

下面是一个测试结果:

D:javajava GoodWindowsExec "copy Test.java Test1.java"

osName: Windows XP

Execing cmd.exe /C copy Test.java Test1.java

OUTPUT已复制 1 个文件。

ExitValue: 0

D:java

下面的测试都能通过(windows xp+jdk1.5)

D:javajava GoodWindowsExec dir

D:javajava GoodWindowsExec Test.java

D:javajava GoodWindowsExec regedit.exe

D:javajava GoodWindowsExec NOTEPAD.EXE

D:javajava GoodWindowsExec first.ppt

D:javajava GoodWindowsExec second.doc

function TempSave(ElementID) { CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value); CommentsPersistDiv.save("CommentXMLStore"); } function Restore(ElementID) { CommentsPersistDiv.load("CommentXMLStore"); document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent"); }

windows怎么运行java程序

JAVA开发的程序可以通过JVM for windows在Windows上运行,但并不能用来开发Windows原生程序,正如现在的HTML5开发的应用可以再Andriod上运行,但并不是安卓的原生应用一样。

Java语言的一个非常重要的特点就是与平台的无关性。而使用Java虚拟机(Java Virtual Machine)是实现这一特点的关键。JVM是(Java虚拟机)的缩写,JVM是一种用于计算设备的规范,它是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟各种计算机功能来实现的。

一般的高级语言如果要在不同的平台上运行,至少需要编译成不同的目标代码。而引入Java语言虚拟机后,Java语言在不同平台上运行时不需要重新编译。Java语言使用Java虚拟机屏蔽了与具体平台相关的信息,使得Java语言编译程序只需生成在Java虚拟机上运行的目标代码(字节码),就可以在多种平台上不加修改地运行。Java虚拟机在执行字节码时,把字节码解释成具体平台上的机器指令执行。这就是Java的能够“一次编译,到处运行”的原因。

如何用java启动windows命令行程序

先请编译和运行下面程序:

import java.util.*;

import java.io.*;

public class BadExecJavac2

{

public static void main(String args[])

{

try

{

Runtime rt = Runtime.getRuntime();

Process proc = rt.exec("javac");

int exitVal = proc.waitFor();

System.out.println("Process exitValue: " + exitVal);

} catch (Throwable t){

t.printStackTrace();

}

}

}

我们知道javac命令,当不带参数运行javac

程序时,它将输出帮助说明,为什么上面程序不产生任何输出并挂起,永不完成呢?java文档上说,由于有些本地平台为标准输入和输出流所提供的缓冲区大小

有限,如果不能及时写入子进程的输入流或者读取子进程的输出流,可能导致子进程阻塞,甚至陷入死锁。所以,上面的程序应改写为:

import java.util.*;

import java.io.*;

public class MediocreExecJavac

{

public static void main(String args[])

{

try

{

Runtime rt = Runtime.getRuntime();

Process proc = rt.exec("javac");

InputStream stderr = proc.getErrorStream();

InputStreamReader isr = new InputStreamReader(stderr);

BufferedReader br = new BufferedReader(isr);

String line = null;

System.out.println("");

while ( (line = br.readLine()) != null)

System.out.println(line);

System.out.println("");

int exitVal = proc.waitFor();

System.out.println("Process exitValue: " + exitVal);

} catch (Throwable t){

t.printStackTrace();

}

}

}

下面是正确的输出:

D:javajava MediocreExecJavac

Usage: javac options

where possible options include:

-g Generate all debugging info

-g:none Generate no debugging info

-g:{lines,vars,source} Generate only some debugging info

-nowarn Generate no warnings

-verbose Output messages about what the compiler is doing

-deprecation Output source locations where deprecated APIs are used

-classpath Specify where to find user class files

-cp Specify where to find user class files

-sourcepath Specify where to find input source files

-bootclasspath Override location of bootstrap class files

-extdirs Override location of installed extensions

-endorseddirs Override location of endorsed standards path

-d Specify where to place generated class files

-encoding Specify character encoding used by source files

-source Provide source compatibility with specified release

-target Generate class files for specific VM version

-version Version information

-help Print a synopsis of standard options

-X Print a synopsis of nonstandard options

-J Pass directly to the runtime system

Process exitValue: 2

D:java

下面是一个更一般的程序,它用两个线程同步清空标准错误流和标准输出流,并能根据你所使用的windows操作系统选择windows命令解释器command.com或cmd.exe,然后执行你提供的命令。

import java.util.*;

import java.io.*;

class StreamGobbler extends Thread

{

InputStream is;

String type; //输出流的类型ERROR或OUTPUT

StreamGobbler(InputStream is, String type)

{

this.is = is;

this.type = type;

}

public void run()

{

try

{

InputStreamReader isr = new InputStreamReader(is);

BufferedReader br = new BufferedReader(isr);

String line=null;

while ( (line = br.readLine()) != null)

{

System.out.println(type + "" + line);

System.out.flush();

}

} catch (IOException ioe)

{

ioe.printStackTrace();

}

}

}

public class GoodWindowsExec

{

public static void main(String args[])

{

if (args.length 1)

{

System.out.println("USAGE: java GoodWindowsExec ");

System.exit(1);

}

try

{

String osName = System.getProperty("os.name" );

System.out.println("osName: " + osName);

String[] cmd = new String[3];

if(osName.equals("Windows XP") ||osName.equals("Windows 2000"))

{

cmd[0] = "cmd.exe" ;

cmd[1] = "/C" ;

cmd[2] = args[0];

}

else if( osName.equals( "Windows 98" ) )

{

cmd[0] = "command.com" ;

cmd[1] = "/C" ;

cmd[2] = args[0];

}

Runtime rt = Runtime.getRuntime();

System.out.println("Execing " + cmd[0] + " " + cmd[1]+ " " + cmd[2]);

Process proc = rt.exec(cmd);

// any error message?

StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

// any output?

StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

// kick them off

errorGobbler.start();

outputGobbler.start();

// any error???

int exitVal = proc.waitFor();

System.out.println("ExitValue: " + exitVal);

} catch (Throwable t){

t.printStackTrace();

}

}

}

下面是一个测试结果:

D:javajava GoodWindowsExec "copy Test.java Test1.java"

osName: Windows XP

Execing cmd.exe /C copy Test.java Test1.java

OUTPUT已复制 1 个文件。

ExitValue: 0

D:java

下面的测试都能通过(windows xp+jdk1.5)

D:javajava GoodWindowsExec dir

D:javajava GoodWindowsExec Test.java

D:javajava GoodWindowsExec regedit.exe

D:javajava GoodWindowsExec NOTEPAD.EXE

D:javajava GoodWindowsExec first.ppt

D:javajava GoodWindowsExec second.doc

function TempSave(ElementID)

{

CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value);

CommentsPersistDiv.save("CommentXMLStore");

}

function Restore(ElementID)

{

CommentsPersistDiv.load("CommentXMLStore");

document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent");

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。