本文目錄一覽:
- 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”);
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/312859.html