public class Test {
public static void main(String[] args) throws Exception {
try {
//execute shell command: df -k .
Process fileSystemDfInfo = Runtime.getRuntime().exec("df -k .");
BufferedReader reader = new BufferedReader(
new InputStreamReader(fileSystemDfInfo.getInputStream()));
String contentLine;
while ((contentLine = reader.readLine()) != null){
//do something with contentLine
System.out.println(contentLine);
}
reader.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
===
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RunSystemCommand {
public static void main(String args[]) {
String s = null;
// system command to run
String cmd = "ls > fred.txt";
// set the working directory for the OS command processor
File workDir = new File("/dir1/dir2");
try {
Process p = Runtime.getRuntime().exec(cmd, null, workDir);
int i = p.waitFor();
if (i == 0) {
BufferedReader stdInput = new BufferedReader(
new InputStreamReader(p.getInputStream()));
// read the output from the command
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
} else {
BufferedReader stdErr = new BufferedReader(
new InputStreamReader(p.getErrorStream()));
// read the output from the command
while ((s = stdErr.readLine()) != null) {
System.out.println(s);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Resource: 1. http://bjyzxxds.iteye.com/blog/460126
本文提供两个Java示例程序,展示如何通过Java执行系统命令并读取命令的输出和错误信息。第一个示例演示了如何执行df -k命令来获取磁盘使用情况,第二个示例则展示了如何执行ls > fred.txt命令并将输出重定向到文件。
223

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



