JAVA利用Runtime执行多条linux命令

本文介绍了一个Java程序如何通过调用Python脚本来处理文件的具体实现方式。该示例使用Runtime类执行Linux shell命令,并通过/bin/sh -c来组合多个命令执行Python脚本,同时展示了如何捕获并打印Python脚本的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void execPythonShell(File file) throws IOException {
  String path = Utils.class.getClassLoader().getResource(“/import.py”)
    .getPath();
  Runtime runtime = Runtime.getRuntime();
  BufferedReader br = null;
  try {
   String[] cmds = new String[] {
     "/bin/sh",
     "-c",
     "cd " + path + "&&python edit_support_export_infor.py "
       + file.getPath() };
   Process process = runtime.exec(cmds);
   br = new BufferedReader(new InputStreamReader(
     process.getInputStream(), "GBK"));
   String tmp = null;
   while ((tmp = br.readLine()) != null) {
    System.out.println("Shell Message : " + tmp);
   }
  } catch (IOException e) {
   logger.error(e);
  } finally {
   br.close();
  }
 }

// -c 意思是执行完成自动关闭,这里多条linux命令通过&&连接到一起

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值