在Linux操作系统上可以执行本地命令,并返回字符串。
在CentOS 6.3上已经测试正常运行。
package com.cz.shell;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Shell {
public static String ec(String command) throws InterruptedException {
String returnString = "";
Process pro = null;
Runtime runTime = Runtime.getRuntime();
if (runTime == null) {
System.err.println("Create runtime false!");
}
try {
pro = runTime.exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
String line;
while ((line = input.readLine()) != null) {
// System.out.println(line);
returnString = returnString + line + "\n";
}
input.close();
output.close();
pro.destroy();
} catch (IOException ex) {
Logger.getLogger(Shell.class.getName()).log(Level.SEVERE, null, ex);
}
return returnString;
}
}
最新内容已更新至 Java Runtime 执行系统命令行程序 //m.ajphoenix.com/linux/24920.html。请参考最新版本。
本文永久更新地址://m.ajphoenix.com/linux/24919.html