Java Runtime.getRuntime()。exec for unix find命令,不带路径

时间:2015-06-23 21:27:07

标签: java linux unix

尝试了多种方式。除了一个特定的子目录之外,删除一组目录下的文件的命令在Linux上运行commmand时工作正常。

当通过Java exec运行时,相同的命令似乎无法识别路径并且一切都被清除。

find /test/filesdir/filexp -maxdepth 2 ! -path "/test/filesdir/filexp/node1/*" -type f -daystart -mtime +1 -delete

尝试escpace字符\之前(“)双引号似乎没什么帮助。

任何想法,请帮助。

使用的java代码:

Process RunCmdLine = Runtime.getRuntime().exec(CommandLine);
RunCmdLine.waitFor();
InputStream stdInput = RunCmdLine.getInputStream();
InputStream stdError = RunCmdLine.getErrorStream();
byte buffer[] = new byte [2048];
for (int read; (read = stdInput.read(buffer)) != -1;) {
System.out.write(buffer, 0, read);
inBuff.append(new String(buffer, 0, read));
}
SystemErrMsg[0] = SystemErrMsg[0] + inBuff.toString();

我从数据库查找中获取命令行字符串 整个查找命令

我在

之前添加了一个sysout(命令行)
Process RunCmdLine = Runtime.getRuntime().exec(CommandLine);

我在服务器上的stdout文件中看到了该命令。它看起来不错,当我在服务器上运行该命令时它工作正常。

1 个答案:

答案 0 :(得分:2)

Runtime.exec(String)声称另一名受害者!

切勿使用此功能。它只有零有效用例。请改用Runtime.exec(String[])版本,或(甚至更好)ProcessBuilder

两者都有两种常用的习语。第一个通过在shell中运行命令来模拟C&C的简单和草率system

// I don't care about security, my homework is due and I just want it to work ;_;
String CommandLine = "find /test/filesdir/filexp -maxdepth 2 " 
    + "! -path \"/test/filesdir/filexp/node1/*\" " 
    + "-type f -daystart -mtime +1 -delete";
Runtime.getRuntime().exec(new String[] { "bash", "-c", CommandLine });

和更接近C execv(char*, char**)的安全且强大的版本:

// I have a strong understanding of UNIX and want a robust solution!
String[] commandArgs = new String[] {
    "find", "/test/filesdir/fileexp", "-maxdepth", "2",
      "!", "-path", "/test/filesdir/filexp/node1/*", "-type", "f",
      "-daystart", "-mtime", "+1", "-delete"
};
Runtime.getRuntime().exec(commandArgs);

第一个只需要你知道如何使用shell。第二个要求您另外知道shell如何在幕后工作,并且不能基于此示例盲目复制。