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");
}
}
javac
java
p.waitFor()
java.lang.UNIXProcess@2524e205
Hello, World
p
p.waitFor();
temp.java:19: error: cannot find symbol
p.waitFor();
^
symbol: variable p
location: class temp
1 error
The Process p
is limited in scope to the try
block
try
try {
Process p = r.exec("ls");
System.out.println(p);
p.waitFor ();
}