【转】runtime总结

来源:互联网 发布:wifi网络延迟测试 编辑:程序博客网 时间:2024/05/21 22:33
调用Runtime.exec方法将产生一个本地的进程
2007年06月11日 星期一 19:20
调用Runtime.exec方法将产生一个本地的进程,并返回一个Process子类的实例,该实例可用于控制进程或取得进程的相关信息. 由于调用Runtime.exec方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO(如stdin,stdou,stderr)都通过Process.getOutputStream(),Process.getInputStream(), Process.getErrorStream()方法重定向给它的父进程了.用户需要用这些stream来向 子进程输入数据或获取子进程的输出. 所以正确执行Runtime.exec("ls")的例程如下:
1
2
3
4
5
6
7
8
9
10
11
12
try{     process = Runtime.getRuntime().exec (command);     InputStreamReader ir=newInputStreamReader(process.getInputStream());     LineNumberReader input = new LineNumberReader (ir);     String line;    while ((line = input.readLine ()) != null)          System.out.println(line);}catch (java.io.IOException e){     System.err.println ("IOException " + e.getMessage());} 


作者:Onlyfor_love
发表时间:2005-4-26 13:19:11

Runtime.exec(“文本“)

文本的内容必须在DOS或平台上可执行,如Runtime.exec(”move c://a.txt c://b//”)就肯定执行不了,所以只能用拆衷的办法,把move c:/a.txt c:/b/写在一个批处理文件T内,然后执行:

Runtime.exec(”t.bat:”)
////////////////////////////////////////////////////////////////////////////////////
Java技巧:使用Runtime.exec重定向本地程序调用

作者: BUILDER.COM
Tuesday, December 31 2002 11:58 AM
Java具有使用Runtime.exec对本地程序调用进行重定向的能力,但是用重定向或者管道进行命令调用将会出错。解决这一问题的办法是通过命令shell运行命令。在Java中调用本地程序会破坏平台独立性规则,但是经常需要这么做才行。

以下是一个简单类的范例,展示了在Unix下运行ls命令的情形:
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
import java.io.BufferedInputStream;import java.io.IOException; public class ExecLs {     static public void main(String[] args) {         String cmd = "ls"         try {             Process ps = Runtime.getRuntime().exec(cmds);             System.out.print(loadStream(ps.getInputStream()));             System.err.print(loadStream(ps.getErrorStream()));        } catch(IOException ioe) {             ioe.printStackTrace();        }    }     // read an input-stream into a String    static String loadStream(InputStream in) throws IOException {        int ptr = 0;         in = new BufferedInputStream(in);         StringBuffer buffer = new StringBuffer();        while( (ptr = in.read()) != -1 ) {             buffer.append((char)ptr);        }        return buffer.toString();    } } 

上述代码中重要的部分是exec方法和命令字符串ls。本程序将输出运行目录下的列表细节。
 
原创粉丝点击