How to implement the following linux command in Java

How to implement it in Java?

grep "Exception" /home/admin/logs/common-error.log |sort |uniq -c |sort -nr

I only know what does this command mean, while have no idea about how to implement it in Java...

Many thanks.

2 answers

  • answered 2018-04-17 05:31 parlad neupane

    here is the sample,

    Process p = Runtime.getRuntime().exec("your command");                                                                                                                                                     
    
    BufferedReader stdInput = new BufferedReader(new 
    InputStreamReader(p.getInputStream()));
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
    }
    

    Detail can be found here here.

  • answered 2018-04-17 05:31 applecrusher

    You can run it as a process within Java as shown below, but remember this will only work in Linux or Mac environments.

    Process p = Runtime.getRuntime().exec("grep \"Exception\" /home/admin/logs/common-error.log |sort |uniq -c |sort -nr
    ");
    p.waitFor();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = "";
    StringBuilder output = new StringBuilder();
    while ((line = reader.readLine()) != null) {
     output.append(line + "\n");
    }
    System.out.println(output.toString());