Java运行Linux命令和Windows命令工具类
程序员文章站
2022-04-15 19:11:40
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * 系统命令执行器 * @author suozq * */public class LocalCmdExecutor {private static Runtime rt=Runtime.getRuntime();private static String charsetName = "utf-8...
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 系统命令执行器
* @author suozq
*
*/
public class LocalCmdExecutor {
private static Runtime rt=Runtime.getRuntime();
private static String charsetName = "utf-8";
static {
String os = System.getProperty("os.name");
if(os.toLowerCase().contains("windows")) {
charsetName="gb2312";
}
}
/**
* 运行系统命令
* @param cmd 例子:exec("javac","-version")或exec(new String[]{"javac","-version"})
* @return
* @throws IOException
*/
public static String exec(String...cmd) throws IOException {
return handleProcess(rt.exec(cmd));
}
/**
* 运行系统命令
* @param cmd 例子:exec("javac -version")
* @return
* @throws IOException
*/
public static String exec(String cmd) throws IOException {
return handleProcess(rt.exec(cmd));
}
private static String handleProcess(Process process) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),charsetName));
for(String s=reader.readLine();s!=null;s=reader.readLine()) {
sb.append(s).append("\n");
}
reader.close();
return sb.toString();
}
public static void main(String[] args) throws IOException {
System.out.println(exec("javac -version"));
}
}
注意
- 推荐使用数组方式,使用字符串最终还是需要转为字符串数组;
-
Runtime
对象是单例模式,无论调用多少次Runtime.getRuntime()
,返回为同一对象; -
rt.exec()
从源码看可以并发调用,并发使用时,资源耗用可能会很大; - 如果命令执行过慢,会导致不能读取到结果,请添加
process.waitFor()
方法,该方法会使当前线程等待直到process子进程结束,0
代表正常结束
本文地址:https://blog.csdn.net/suo082407128/article/details/107386044
上一篇: 生玉米要蒸多久?玉米怎么保存?
下一篇: 荐 吐血总结-IDEA的神级插件