十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
Java运行命令行并获取返回值,下面以简单的Java执行ping命令(ping 127.0.0.1 -t
目前创新互联公司已为数千家的企业提供了网站建设、域名、虚拟主机、网站运营、企业网站设计、沙河口网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。
)为例,代码如下:
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运行时环境有关的类,这个类是Singleton的。Runtime.getRuntime()可以取得当前JVM的运行时环境,这也是在Java中唯一一个得到运行时环境的方法。Runtime.exec()方法就是执行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();
}
}
}
先请编译和运行下面程序:
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");
}