Darshil Chauhan Darshil Chauhan - 2 months ago 7
Java Question

Java: cannot find symbol but no exception thrown

I am trying to run a system command in java file as shown in the answer here: How to execute system commands (linux/bsd) using Java

Below is my code (temp.java):

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class temp
{
public static void main(String[] args)

{
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec("ls");
System.out.println(p);
}
catch (Exception ex) {
System.out.println(ex);
}
p.waitFor(); //this line causes the problem

System.out.println("Hello, World");
}
}


When I compile and run it (using
javac
and
java
) in terminal without the line
p.waitFor()
, it runs fine and gives the following output:

java.lang.UNIXProcess@2524e205
Hello, World


So it seems that
p
is being created. But when I include the line
p.waitFor();
, and compile and run it the same way, it gives the following error:

temp.java:19: error: cannot find symbol
p.waitFor();
^
symbol: variable p
location: class temp
1 error


What is the problem?

EDIT:

The question that this question is being claimed to be duplicate of, is very broad question. I had a specific problem. I had gone through it earlier but could not figure out the problem. Please remove the duplicate mark if possible.

Answer

The Process p is limited in scope to the try block

try

try {
        Process p = r.exec("ls"); 
        System.out.println(p);
        p.waitFor ();
}
Comments