0

I executed this code:

Process proc = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
System.out.println(proc.toString());
String proc1 = proc.toString();

But I am not able to get the content of kafka_metrics.sh. Instead I am getting java.lang.UNIXProcess@5fd0d5ae as output. What should I include so that I can get the content of that file?

Kenster
  • 23,465
  • 21
  • 80
  • 106

2 Answers2

0

May this is what you are looking for.

Process proc = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
String s = null;
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
}

// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
  • sorry, i have updated my code. I mistakenly wrote p instead of proc while initializing the two BufferedReader objects. – Wasi Ahmad Oct 26 '16 at 03:16
  • System.out.println("Here is the standard output of the command:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); String s1 = s; } System.out.println("String read------->"+stdInput.readLine()); String s1 = stdInput.readLine(); I wrote this code but whenever it comes out of while string is losing it's value so to get that same what should I do. I mean I am getting null value but I want the content of file. – Srikarsh Vardhanreddy Kolanu Oct 26 '16 at 03:50
  • Content of file means the content of metrics.sh? In that case you can directly read that file. The piece of example i provided will give you the output of the command that you are executing through Java's Runtime, that's it. – Wasi Ahmad Oct 26 '16 at 03:56
0

You are printing the Process object.

to get the content of the executed process you need to take the input stream and pass that stream to the reader

    Process process = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
    InputStream is = process.getInputStream();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        br.lines().forEach(System.out::println);
    }
Saravana
  • 12,647
  • 2
  • 39
  • 57