chunky
chunky

Reputation: 75

Running linux command in java

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?

Upvotes: 0

Views: 2090

Answers (1)

Andrii Abramov
Andrii Abramov

Reputation: 10751

If you want to run any command from Java ensure that executable of this file is present in PATH environment variable.

Or at least you have to set working directory to /usr/bin or similar.

One more solution is to use absolute path to executable, e.g.:

Runtime.getRuntime().exec("/usr/bin/ls");

But it is bad way to specify absolute path to any file.

Why don't you use File#listFiles()?

Upvotes: 4

Related Questions