【问题标题】:Runtime.getRuntime().exec(command) always return 1Runtime.getRuntime().exec(command) 总是返回 1
【发布时间】:2015-12-30 20:56:53
【问题描述】:

我正在尝试在我的 mac 上运行以下代码

 String command = "find /XXX/XXX/Documents/test1* -mtime +10 -type f -delete";

Process p = null;
p = Runtime.getRuntime().exec(command);
p.getErrorStream();
int exitVal = p.waitFor();

exitVal 始终为 1,不会删除文件 有什么想法吗??

【问题讨论】:

  • 尝试使用find的完整路径
  • 你试过阅读ProcessInputStreamErrorStream吗?您还应该使用ProcessBuilder

标签: java shell


【解决方案1】:

根据我的实验,find 在找不到任何结果时会返回1 (find: /XXX/XXX/Documents/test1*: No such file or directory)

首先,您应该真正使用ProcessBuilder,这解决了包含空格的参数的问题,允许您重定向输入/错误流以及指定命令的开始位置(如果您需要它)。

所以,玩弄它,像这样的东西,似乎对我有用(MacOSX)......

ProcessBuilder pb = new ProcessBuilder(
        new String[]{
            "find", 
            "/XXX/XXX/Documents/test1",
            "-mtime", "+10",
            "-type", "f",
            "-delete"
        }
);
pb.redirectErrorStream(true);
try {
    Process p = pb.start();
    InputStream is = p.getInputStream();
    int in = -1;
    while ((in = is.read()) != -1) {
        System.out.print((char)in);
    }
    int exitWith = p.exitValue();
    System.out.println("\nExited with " + exitWith);
} catch (IOException exp) {
    exp.printStackTrace();
}

【讨论】:

  • 这很好用,刚刚在 int exitWith = p.exitValue(); 之前添加我添加了 p.waitFor() 以防止异常。非常感谢
猜你喜欢
  • 2011-03-28
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 2015-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多