使用java执行linux命令或windows命令
一、执行linux命令
写一个静态的通用的linux命令执行方法:
public static String execLinuxCMD(String cmdStr){
try {
String[] cmd = new String[] { "/bin/sh", "-c", cmdStr };
Process ps = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
String result = sb.toString();
log.info("linux命令执行成功。 cmd:{}, result:{} ",cmdStr, result);
return result;
} catch (Exception e) {
log.error("linux命令执行失败。cmd:{}",cmdStr,e);
}
return null;
}
二、执行windows命令
写一个通用的静态的windows命令执行方法
public static String execWinCMD(String cmdStr){
BufferedReader br = null;
Process p = null;
String result = null;
try {
Runtime runtime = Runtime.getRuntime();
p = runtime.exec(cmdStr);
br = new BufferedReader(new InputStreamReader(p.getInputStream(),"GB2312"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
// log.info("windows命令执行成功。 cmd:{}, result:{} ",cmdStr, sb.toString());
return sb.toString();
} catch (Exception e) {
log.error("windowd命令执行失败。cmd:{}",cmdStr,e);
}finally {
if (br != null)
{
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (p != null){
p.destroy();
}
}
return null;
}
三、测试
测试: 根据不同平台计算文件md5值
// 判断当前机器是否是windows
public static Boolean isWindows(){
String os = System.getProperty("os.name");
return os.toLowerCase().startsWith("win");
}
// 根据不同平台计算md5
public static void main(String[] args){
if(isWindows()){
String r = execWinCMD("md5 /data/data.txt");
} else if (isMac()){
String r = execLinuxCMD("md5 /data/data.txt");
}
}
————————————————
版权声明:本文为CSDN博主「诸葛小猿」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wuxiaolongah/article/details/129394150