Java execute command line program 'find' returns error

冷暖自知 提交于 2019-12-30 20:26:10

问题


The following works from the terminal no problem

find testDir -type f -exec md5sum {} \;

Where testDir is a directory that contains some files (for example file1, file2 and file3).

However, I get an error using the following in Java

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("find testDir -type f -exec md5sum {} \\;");

The error is

find: missing argument to `-exec'

I believe I am escaping the characters correctly. I have tried several different formats and I cannot get this to work.

UPDATE @jtahlborn answered the question perfectly. But the command has now changed slightly to sort each file in the dir before calculating the md5sum and is as follows (I have already accepted the excellent answer for the original question so I'll buy somebody a beer if they can come up with the format for this. I have tried every combination I can think of following the answer below with no success.)

"find testDir -type f -exec md5sum {} + | awk {print $1} | sort | md5sum ;"

NEW UPDATE

For pipe, you need a shell so I ended up with this, which works great and you can still get the output.

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[] 
{
    "sh", "-l", "-c", "find " + directory.getPath() + " -type f -exec md5sum {} + | awk '{print $1}' | sort | md5sum"
});

回答1:


use the multi-argument call to exec (otherwise you can get bitten by escape rules). also, since you aren't calling from a shell script, you don't need to escape the semicolon:

Process pr = rt.exec(new String[]{"find", "testDir", "-type", "f", "-exec", "md5sum", "{}", ";"});



回答2:


For things like pipe, you need a shell which you don't get with Runtime.exec.

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[] 
{
    "sh", "-l", "-c", "find " + directory.getPath() + " -type f -exec md5sum {} + | awk '{print $1}' | sort | md5sum"
});


来源:https://stackoverflow.com/questions/10704889/java-execute-command-line-program-find-returns-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!