Java code operation executes linux/windows commands
1. Modify the execution in the java code to determine whether it is a windows environment setting modification time
try{
/**
* 获取操作系统的名称
* */
String name = System.getProperty("os.name");
if(name.contains("Windows")){ // Window 操作系统
String cmd = " cmd /c time 19:50:00";
Runtime.getRuntime().exec(cmd); // 修改时间
cmd = " cmd /c date 2012-01-02";
Runtime.getRuntime().exec(cmd); // 修改日期
} else{ // 一般都是在linux 运行
String command = "sudo date -s " + formatDateStr;
Runtime.getRuntime().exec(command);
dataLog.info("change Date success");
command = "sudo date -s " + formatTimeStr;
Runtime.getRuntime().exec(command);
dataLog.info("change Time success");
}
}catch(Exception e){
e.printStackTrace();
2. Generally, there is no return value if the Linux command is executed successfully. We can judge that there is no return value after receiving the processing, then the execution is successful.
**String command = "sudo mkdir /home/ww"; // 在home 下面创建文件夹
try {
InputStream rst = Runtime.getRuntime().exec(command).getInputStream();
dataLog.info("change IP Phase one");
byte[] rt = new byte[256];
len = rst.read(rt);
// linux 执行命令,正确时不会返回数据
if (len > 0) {
System.out.println("执行失败");
} else {
System.out.println("执行成功");
}
} catch (Exception e) {
errorLog.error("change IP error !");
}**