
public class Linux {
public static void main(String[] args) throws IOException {
//将根目录下的文件列出并将结果写入 /tmp/list.out
Process p = Runtime.getRuntime().exec("ls -al /")
InputStream in = p.getInputStream()
OutputStream out = new FileOutputStream("/tmp/list.out")
byte[] b = new byte[1024]
int r
while((r=in.read(b))>-1)
out.write(b,0,r)
out.flush()
out.close()
}
}
Java可以通过Runtime调用Linux命令,形式如下:
Runtime.getRuntime().exec(command)
但是这样执行时没有任何输出,因为调用Runtime.exec方法将产生一个本地的进程,并返回一个Process子类的实例(注意:Runtime.getRuntime().exec(command)返回的是一个Process类的实例)该实例可用于控制进程或取得进程的相关信息。
由于调用Runtime.exec方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO(如stdin,stdou,stderr)都通过Process.getOutputStream(),Process.getInputStream(),Process.getErrorStream()方法重定向给它的父进程了。
用户需要用这些stream来向子进程输入数据或获取子进程的输出,下面的代码可以取到linux命令的执行结果:
try{
String[]cmd=newString[]{”/bin/sh”,“-c”,”ls“}
Processps=Runtime.getRuntime().exec(cmd)
BufferedReaderbr=newBufferedReader(newInputStreamReader(ps.getInputStream()))
StringBuffersb=newStringBuffer()
Stringline
while((line=br.readLine())!=null){
sb.append(line).append(”\n”)
}
Stringresult=sb.toString()
System.out.println(result)
}catch(Exceptione){
e.printStackTrace()
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)