0

How can I store the output of a grep in a file using Java?

I'm using Runtime and Process to execute the grep, then I read the InputStream

BufferedReader stdInput = new BufferedReader(new InputStreamReader(pr.getInputStream()));

and now I'd like to store the content of the grep in a file, but I'm getting an empty file.

With

String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

I am correctly seeing the grep's output. However, when I try to write it to a file, the file is empty.

PrintWriter writer = null;
writer = new PrintWriter("grep__output", "UTF-8");
writer.println(s);
writer.close();

Also, I tried to directly writing to file in the above while (previously creating the file), but it's the same.

2
  • 1
    Why use grep? Why not use a Pattern? Commented Apr 1, 2014 at 20:50
  • grep was just an example. I'm interested in any bash tool basically. Commented Apr 1, 2014 at 21:27

1 Answer 1

1

You need to have the println in the loop that's reading. You are likely just writing null to the file.

PrintWriter writer = new PrintWriter("grep__output", "UTF-8");
String s = null;
while ((s = stdInput.readLine()) != null) {
   writer.println(s);
} 
writer.close();
Sign up to request clarification or add additional context in comments.

1 Comment

OMG, it's working now. I swear I tried exactly this same code, in fact, read my last sentence in the question xD.

Your Answer

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