Dhruv
Dhruv

Reputation: 10693

Execute grep command on Linux and capture result

I am trying to execute grep command on the linux using the following java code, but I am not able to capture output. I am getting always null in the output

Process p;
        String output = null;
        try {
            String command = "grep searchString filename.txt";
            System.out.println("Running command: " + command);

            p = Runtime.getRuntime().exec(command);

            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

            if (null != output) {

                while ((output = br.readLine()) != null)
                    System.out.println(output);
            } 

            p.waitFor();
            System.out.println("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {
            e.printStackTrace();

    }

How to capture the output? Is there any third party library or some better way to execute the command on linux and capture the output?

Upvotes: 0

Views: 2101

Answers (1)

oardic
oardic

Reputation: 212

output has not been assigned when you do if check. Change your code like below:

    Process p;
    String output = null;
    try {
        String command = "grep searchString filename.txt";
        System.out.println("Running command: " + command);

        p = Runtime.getRuntime().exec(command);
        p.waitFor();

        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

            while ((output = br.readLine()) != null) {
                System.out.println(output);
                // Process your output here
            }

        System.out.println("exit: " + p.exitValue());
        p.destroy();
    } catch (Exception e) {
        e.printStackTrace();

}

Upvotes: 1

Related Questions