
可以使用Java Process类,下面是一些例子:
Process类是一个抽象类,方法都是抽象的,它封装了一个进程,也就是一个可执行的程序 该类提供进程的输入、执行输出到进程、等待进程的完成和检查进程的退出状态及销毁进程的方法ProcessBuilder.start()和Runtime.exec方法创建一个本机进程并返回Process子类的一个实例,该实例可以控制进程并获取相关的信息
其它的概要请参考JDK文档
下面就开始举几个简单的示例:
(1)执行简单的DOS命令,如打开一个记事本
Java代码
package com.iwtxokhtd.other
import java.io.IOException
public class ProcessTest {
public static void main(String[] args) {
try {
Process proc=Runtime.getRuntime().exec("notepad")
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
[java] view plain copy
package com.iwtxokhtd.other
import java.io.IOException
public class ProcessTest {
public static void main(String[] args) {
try {
Process proc=Runtime.getRuntime().exec("notepad")
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
(2)使用它的其它构造方法执行相关的命令,如下例:
Java代码
package com.iwtxokhtd.other
import java.io.IOException
public class ProcessTest {
public static void main(String[] args) {
try {
String exeFullPathName="C:/Program Files/Internet Explorer/IEXPLORE.EXE"
String message="www.google.com"
String []cmd={exeFullPathName,message}
Process proc=Runtime.getRuntime().exec(cmd)
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
[java] view plain copy
package com.iwtxokhtd.other
import java.io.IOException
public class ProcessTest {
public static void main(String[] args) {
try {
String exeFullPathName="C:/Program Files/Internet Explorer/IEXPLORE.EXE"
String message="www.google.com"
String []cmd={exeFullPathName,message}
Process proc=Runtime.getRuntime().exec(cmd)
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
执行上述命令可以打开Google网站
(3)列出系统正在运行的所有进程信息
Java代码
package com.iwtxokhtd.other
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
public class ListAllProcessTest {
//列出所有的进程信息
public static void main(String[] args) {
BufferedReader br=null
try {
Process proc=Runtime.getRuntime().exec("tasklist")
br=new BufferedReader(new InputStreamReader(proc.getInputStream()))
@SuppressWarnings("unused")
String line=null
System.out.println("打印所有正在运行的进程信息")
while((line=br.readLine())!=null){
System.out.println(br.readLine())
}
} catch (IOException e) {
e.printStackTrace()
}finally{
if(br!=null){
try {
br.close()
} catch (Exception e) {
e.printStackTrace()
}
}
}
}
}
[java] view plain copy
package com.iwtxokhtd.other
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
public class ListAllProcessTest {
//列出所有的进程信息
public static void main(String[] args) {
BufferedReader br=null
try {
Process proc=Runtime.getRuntime().exec("tasklist")
br=new BufferedReader(new InputStreamReader(proc.getInputStream()))
@SuppressWarnings("unused")
String line=null
System.out.println("打印所有正在运行的进程信息")
while((line=br.readLine())!=null){
System.out.println(br.readLine())
}
} catch (IOException e) {
e.printStackTrace()
}finally{
if(br!=null){
try {
br.close()
} catch (Exception e) {
e.printStackTrace()
}
}
}
}
}
(4)判断一个具体的进程是否正在运行,如下例:
Java代码
package com.iwtxokhtd.other
import java.io.BufferedReader
import java.io.InputStreamReader
public class FindProcessExeTest
{
public static void main(String []args){
if(findProcess("QQ.exe")){
System.out.println("------判断指定的进程是否在运行------")
System.out.println("QQ.exe该进程正在运行!")
}else{
System.out.println("------判断指定的进程是否在运行------")
System.out.println("QQ.exe该进程没有在运行!")
}
}
public static boolean findProcess(String processName){
BufferedReader br=null
try{
//下面这句是列出含有processName的进程图像名
Process proc=Runtime.getRuntime().exec("tasklist /FI /"IMAGENAME eq "+processName+"/"")
br=new BufferedReader(new InputStreamReader(proc.getInputStream()))
String line=null
while((line=br.readLine())!=null){
//判断指定的进程是否在运行
if(line.contains(processName)){
return true
}
}
return false
}catch(Exception e){
e.printStackTrace()
return false
}finally{
if(br!=null){
try{
br.close()
}catch(Exception ex){
}
}
}
}
}
[java] view plain copy
package com.iwtxokhtd.other
import java.io.BufferedReader
import java.io.InputStreamReader
public class FindProcessExeTest
{
public static void main(String []args){
if(findProcess("QQ.exe")){
System.out.println("------判断指定的进程是否在运行------")
System.out.println("QQ.exe该进程正在运行!")
}else{
System.out.println("------判断指定的进程是否在运行------")
System.out.println("QQ.exe该进程没有在运行!")
}
}
public static boolean findProcess(String processName){
BufferedReader br=null
try{
//下面这句是列出含有processName的进程图像名
Process proc=Runtime.getRuntime().exec("tasklist /FI /"IMAGENAME eq "+processName+"/"")
br=new BufferedReader(new InputStreamReader(proc.getInputStream()))
String line=null
while((line=br.readLine())!=null){
//判断指定的进程是否在运行
if(line.contains(processName)){
return true
}
}
return false
}catch(Exception e){
e.printStackTrace()
return false
}finally{
if(br!=null){
try{
br.close()
}catch(Exception ex){
}
}
}
}
}
其它的用法可以参考JDK文档,这里就不一一举例,毕竟它用得不多。
1、执行DOS的内部命令如果要执行一条DOS内部命令,有两种方法。一种方法是把命令解释器包含在exec()的参数中。例如,执行dir命令,在NT上, 可写成exec("cmd.exe /c dir"),在windows 95/98下,可写成“command.exe /c dir”,其中参数“/c”表示命令执行后关闭Dos立即关闭窗口。另一种方法是,把内部命令放在一个批命令my_dir.bat文件中,在Java程序中写成exec("my_dir.bat")。如果仅仅写成exec("dir"),Java虚拟机则会报运行时错误。前一种方法要保证程序的可移植性,需要在程序中读取运行的 *** 作系统平台,以调用不同的命令解释器。后一种方法则不需要做更多的处理。
2、打开一个不可执行的文件
打开一个不可执行的文件,但该文件存在关联的应用程序,则可以有两种方式。 以打开一个word文档a.doc文件为例,Java中可以有以下两种写法:
exec("start .\\a.doc")
exec(" c:\\Program Files\\Microsoft Office\\office\\winword.exe .\\a.doc")
显然,前一种方法更为简捷方便。
3、执行一个有标准输出的DOS可执行程序
在windows平台上,运行被调用程序的DOS窗口在程序执行完毕后往往并不会自动关闭,从而导致Java应用程序阻塞在waitfor( )。导致该现象的一个可能的原因是,该可执行程序的标准输出比较多,而运行窗口的标准输出缓冲区不够大。解决的办法是,利用Java提供的Process类提供的方法让Java虚拟机截获被调用程序的DOS运行窗口的标准输出,在waitfor()命令之前读出窗口的标准输出缓冲区中的内容。一段典型的程序如下:
...
String ls_1
Process process = Runtime.getRuntime().exec("cmd /c dir \\windows")
BufferedReader bufferedReader = new BufferedReader( \
new InputStreamReader(process.getInputStream())
while ( (ls_1=bufferedReader.readLine()) != null)
System.out.println(ls_1)
process.waitfor( )
...
先请编译和运行下面程序: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:\java>java MediocreExecJavac
Usage: javac <options>
where possible options include:
-g Generate all debugging info
-g:noneGenerate no debugging info
-g:{lines,vars,source} Generate only some debugging info
-nowarnGenerate 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
-endorseddirsOverride location of endorsed standards path
-d Specify where to place generated class files
-encodingSpecify 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:\java>java 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:\java>java GoodWindowsExec dir
D:\java>java GoodWindowsExec Test.java
D:\java>java GoodWindowsExec regedit.exe
D:\java>java GoodWindowsExec NOTEPAD.EXE
D:\java>java GoodWindowsExec first.ppt
D:\java>java 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")
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)