首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

java调用linux下令(转)

2012-11-10 
java调用linux命令(转)package com.xlm.otherimport java.io.ByteArrayOutputStreamimport java.io.IOEx

java调用linux命令(转)
package com.xlm.other;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class TestLinux
{

public static void main(String[] args)
{
String[] s = new String[] { "ping", "www.baidu.com" };

String test = TestLinux.exec(s);
System.out.println(test);
}

/** 执行Linux命令,并返回执行结果。 */
public static String exec(String[] args)
{
String result = "";
ProcessBuilder processBuilder = new ProcessBuilder(args);
Process process = null;
InputStream errIs = null;
InputStream inIs = null;
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read = -1;
process = processBuilder.start();
errIs = process.getErrorStream();
while ((read = errIs.read()) != -1)
{
baos.write(read);
}
baos.write('\n');
inIs = process.getInputStream();
while ((read = inIs.read()) != -1)
{
baos.write(read);
}
byte[] data = baos.toByteArray();
result = new String(data);
} catch (IOException e)
{
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
if (errIs != null)
{
errIs.close();
}
if (inIs != null)
{
inIs.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
if (process != null)
{
process.destroy();
}
}
return result;
}

}

热点排行