从java运行Linux命令

时间:2014-03-28 06:26:36

标签: java linux

我试图从java运行命令。但命令没有执行。任何人都可以指出为什么?

 String path = dest+"/info_updated.csv";
     File file = new File(path);
    String command = "sed -i '/" + subscriberId + "/d' "+file;
    System.out.println("command "+command);

       Runtime run = Runtime.getRuntime();

          Process p = null;
          try {
            p = run.exec(command);

            InputStream errorStream = p.getErrorStream();
            p.waitFor();

          } catch (IOException ioe) {
            ioe.printStackTrace();
            System.out.println("ERROR.RUNNING.CMD");
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            p.destroy();
          }
          return true;
  }

在日志中正确打印命令。

command sed -i '/L13876110226750000/d' /usr/share/apache-tomcat-6.0.37/webapps/SMS/info_updated.csv

但它没有执行。

1 个答案:

答案 0 :(得分:2)

您可以在命令之前添加/bin/sh -c并尝试。

像这样:

String[] command = {"/bin/sh", "-c", "sed -i '/" + subscriberId + "/d' "+file};
Process p = run.exec(command);