Java運(yùn)行命令行并獲取返回值,下面以簡單的Java執(zhí)行ping命令(ping 127.0.0.1 -t
目前創(chuàng)新互聯(lián)公司已為數(shù)千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬主機(jī)、網(wǎng)站運(yùn)營、企業(yè)網(wǎng)站設(shè)計、沙河口網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
)為例,代碼如下:
Process?p?=?Runtime.getRuntime().exec("ping?127.0.0.1?-t");
Process?p?=?Runtime.getRuntime().exec("javac");
InputStream?is?=?p.getInputStream();
BufferedReader?reader?=?new?BufferedReader(new?InputStreamReader(is));
String?line;
while((line?=?reader.readLine())!=?null){
System.out.println(line);
}
p.waitFor();
is.close();
reader.close();
p.destroy();
}
使用Runtime類,他是一個與JVM運(yùn)行時環(huán)境有關(guān)的類,這個類是Singleton的。Runtime.getRuntime()可以取得當(dāng)前JVM的運(yùn)行時環(huán)境,這也是在Java中唯一一個得到運(yùn)行時環(huán)境的方法。Runtime.exec()方法就是執(zhí)行cmd命令的方法。
舉例
import?java.io.BufferedReader;
import?java.io.IOException;
import?java.io.InputStreamReader;
import?java.util.ArrayList;
import?java.util.HashMap;
public?class?Test?{
public?static?void?main?(String[]?args)?{
excuteCommand("ipconfig");
excuteCommand("ping?10.141.26.50");
}
public?static?void??excuteCommand(String?command)
{
Runtime?r?=?Runtime.getRuntime();
Process?p;
try?{
p?=?r.exec(command);
BufferedReader?br?=?new?BufferedReader(new?InputStreamReader(p
.getInputStream()));
String?inline;
while?((inline?=?br.readLine())?!=?null)?{
System.out.println(inline);
}
br.close();
}?catch?(IOException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
}
}
先請編譯和運(yùn)行下面程序:
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命令,當(dāng)不帶參數(shù)運(yùn)行javac
程序時,它將輸出幫助說明,為什么上面程序不產(chǎn)生任何輸出并掛起,永不完成呢?java文檔上說,由于有些本地平臺為標(biāo)準(zhǔn)輸入和輸出流所提供的緩沖區(qū)大小
有限,如果不能及時寫入子進(jìn)程的輸入流或者讀取子進(jìn)程的輸出流,可能導(dǎo)致子進(jìn)程阻塞,甚至陷入死鎖。所以,上面的程序應(yīng)改寫為:
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
下面是一個更一般的程序,它用兩個線程同步清空標(biāo)準(zhǔn)錯誤流和標(biāo)準(zhǔn)輸出流,并能根據(jù)你所使用的windows操作系統(tǒng)選擇windows命令解釋器command.com或cmd.exe,然后執(zhí)行你提供的命令。
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();
}
}
}
下面是一個測試結(jié)果:
D:\javajava GoodWindowsExec "copy Test.java Test1.java"
osName: Windows XP
Execing cmd.exe /C copy Test.java Test1.java
OUTPUT已復(fù)制 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");
}