1

I am trying to run "cut" inside a java program, but I am lost in terms of how to split the array of commands. My program in the command line is the following:

cut file.txt -d' ' -f1-2  > hits.txt

And I am trying to run it inside java like this

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[]{"file.txt"," -d' ' -f1-2 "," > hits.txt"});
pr.waitFor();

But I get the following runtime error

Exception in thread "main" java.io.IOException: Cannot run program "cut file.txt": java.io.IOException: error=2, No such file or directory

I attribute this error to the array of Strings I am using as exec commands. Any ideas on how to do this? Also any known documentation on the issue. Thanks

Julio Diaz
  • 9,067
  • 19
  • 55
  • 70
  • `pr2` and `rt2`? Please fix your variable names. – Adam Norberg Mar 21 '12 at 22:36
  • It looks like either the user that runs the java process does not have permission to the file `file.txt`, or, more likely, file.txt is not in the same directory from where you are running the java process. You may correct the relative path or switch to an absolute path. – Brad Mar 21 '12 at 22:36
  • 2
    Is this the exact code? Shouldn't cut be in the command array? – Matt Harrison Mar 21 '12 at 22:38
  • @MattHarrison this is exactly what I was asking – Julio Diaz Mar 22 '12 at 15:37

2 Answers2

1

If you want output redirection, you have to do it yourself. > hits.txt will not do what you want. Redirecting stdout from a process called by exec is covered in another StackOverflow question.

The error you're showing isn't consistent with the source code you've listed here- there's no source for cut, for one thing. It's definitely trying to understand cut file.txt to be the complete relative path to a single executable with a space in its name, which is almost certainly not what you want. It would be easier to troubleshoot this with correct code.

Community
  • 1
  • 1
Adam Norberg
  • 3,028
  • 17
  • 22
1

Make either an script for bash:

"/bin/bash" "-c" "cut file.txt -d' ' -f1-2  > hits.txt"

or split

"cut" "file.txt" "-d" "' '" "-f" "1-2" 

The error message clearly says:

Cannot run program "cut file.txt"

so it interprets "cut file.txt" as a single programname with a blank inside.

Your problem starts with the redirection, because you can't redirect the output that way:

"cut" "file.txt" "-d" "' '" "-f" "1-2" ">" "hits.txt"

You have to handle input and output streams. It might be a better idea to implement cut in Java, to get a portable solution, or call a script which the user may specify on commandline or in a config file, so that it can be adapted for Windows or other platforms.

Calling /bin/bash and redirecting there should work - on unix like systems.

user unknown
  • 35,537
  • 11
  • 75
  • 121
  • 1
    @JulioDiaz: `-c` means, here follows a command. see `bash --help`. The command is the third String, which gets parsed as a whole script by bash. – user unknown Mar 22 '12 at 20:09