0

I am running grep command via my Java program. Running grep on the command line sometimes writes an error on stderr of the kind: No such file or directory. I want to detect in my Java program whenever this error happens as a result of executing the grep command via the program. How can I achieve this goal of mine? This is what I've written so far:

    Runtime rt = Runtime.getRuntime();
    String[] cmd = {"/bin/sh", "-c", "grep -c 'Search_String' /path/to/file(s)/being/searched"};
    Process proc = rt.exec(cmd);
    BufferedReader is = new BufferedReader(new 
    InputStreamReader(proc.getInputStream()));
    String line;
    while ((line = is.readLine()) != null) {
        System.out.println(line);
    }
6
  • 1
    Any reason you can't check that the file exists before passing it to grep? Commented Apr 24, 2017 at 20:59
  • 1
    Check the exitValue. Grep returns 0 for success. If it returns a non-zero value, you're going to have to parse the output. Commented Apr 24, 2017 at 21:04
  • @JoeC I can check but this would make it more comfortable for me when I am trying to run the command against lots of files Commented Apr 24, 2017 at 21:11
  • 1
    For your code: int retVal = proc.waitFor(); // wait for return value Commented Apr 24, 2017 at 21:34
  • 1
    Don't check Process.exitValue(). It won't be there until it returns. It creates another Thread to execute the command. waitFor() will wait until it returns. Commented Apr 24, 2017 at 21:40

1 Answer 1

1

You can detect if the process returned with an error; as @Dakoda mentions, exitValue() won't have the exit value until the process ends, but using waitFor() will block until the process ends and returns the exit value:

int rv = rt.waitFor();
if (rv != 0) { ... }

Error output is usually on stderr rather than stdout, so to read errors you'd use:

BufferedReader is = new BufferedReader(
  new InputStreamReader(proc.getErrorStream()));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.