Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java execute command line program 'find' returns error

Tags:

java

find

bash

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"
});
like image 539
Peter Kelly Avatar asked May 22 '12 15:05

Peter Kelly


1 Answers

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", "{}", ";"});
like image 198
jtahlborn Avatar answered Sep 22 '22 21:09

jtahlborn