Java本地执行linux命令的方法,程序如下:
public String executeLinuxCmd(String cmd) {
System.out.println("开始执行命令: " + cmd);
Runtime run = Runtime.getRuntime();
try {
Process process = run.exec(cmd);
InputStream in = process.getInputStream();
StringBuffer out = new StringBuffer();
byte[] b = new byte[8192];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
System.out.println("命令执行结果:" + out.toString());
in.close();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
本文介绍了一种使用Java程序执行Linux命令的方法。通过Runtime类的getRuntime()方法获取运行时对象,然后调用exec()方法执行命令。执行结果通过输入流读取并转换为字符串输出。
1万+

被折叠的 条评论
为什么被折叠?



