本文主要是介绍Java 执行 Linux 指令,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class MakeFile {
public static void main(String[] args) throws IOException {
Long startTime = 1551434400000L; // 开始时间
Long endTime = 1637920800000L; // 结束时间
String basePath = "/home/backup/"; // 文件基础目录
while(startTime <= endTime) {
// 获取时间字符串
Date date = new Date(startTime);
DateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
String dateStr = formatter.format(date);
//更新系统时间
String cmdChangeTime = "date -s \"" + dateStr + "\"";
executeNewFlow(Collections.singletonList(cmdChangeTime));
System.out.println(cmdChangeTime);
String cmdMakeFile = "mkdir -p " + basePath + dateStr.substring(0,4) + "/" + dateStr.substring(0,10);
executeNewFlow(Collections.singletonList(cmdMakeFile));
System.out.println(cmdMakeFile);
startTime += 7*24*3600*1000;
}
}
/**
* java 执行 linux 指令方法 executeNewFlow(Collections.singletonList("cd /home")); 通过这种方式调用指令
* @param commands
* @return
*/
public static List<String> executeNewFlow(List<String> commands) {
List<String> rspList = new ArrayList<String>();
Runtime run = Runtime.getRuntime();
try {
Process proc = run.exec("/bin/bash", null, null);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
for (String line : commands) {
out.println(line);
}
out.println("exit");// 这个命令必须执行,否则in流不结束。
String rspLine = "";
while ((rspLine = in.readLine()) != null) {
System.out.println(rspLine);
rspList.add(rspLine);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return rspList;
}
}
这篇关于Java 执行 Linux 指令的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!