I want to run "ls" command in java and my code is- Note:- I am using WINDOWS.
import java.io.IOException;
public class Example
{
public void fn()
{
Runtime run = Runtime.getRuntime();
Process p = null;
String cmd = "ls";
try {
p = run.exec(cmd);
p.getErrorStream();
p.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
} finally {
p.destroy();
}
}
public static void main(String[] args) throws IOException
{
Example sp = new Example();
sp.fn();
}
}
but I am getting following error while running this code in eclipse-
java.io.IOException: Cannot run program "ls": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at Example.fn(Example.java:12)
at Example.main(Example.java:28)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 6 more
Exception in thread "main" ERROR.RUNNING.CMD
java.lang.NullPointerException
at Example.fn(Example.java:23)
at Example.main(Example.java:28)
what needs to be corrected? what library, etc. should I add to execute this piece of code?
I want to run "ls" command in javaAre you sure? Because if what you need is a listing of files on the system, this is one terrible way to do it for multiple reasonsrun.exec("bash", "-c", "ls");