Java 执行 Linux 指令
2022/2/16 7:11:40
本文主要是介绍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 指令的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?