2

i tried to run linux command from jar file, but i always get this error:

java.io.IOException: Cannot run program "ls": error=13, Permission denied.

here is my code:

String s;
    Process p;
    String cmd= "ls";

    try {
        Runtime run = Runtime.getRuntime();
        p = run.exec(cmd);
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

        while ((s = br.readLine()) != null){
        System.out.println("line: " + s);
        }

        p.waitFor();
        System.out.println ("exit: " + p.exitValue());
        p.destroy();

    } catch (Exception e) {
        System.out.println(e);
    }

thanks for your time.

UPDATE: For me, my solution is: i had to reinstall my OS and JDK, everything is working now.

9
  • Sounds like you have a file called ls that's not an executable program. Try changing the command to "/bin/ls" Commented Mar 26, 2020 at 2:00
  • same error: java.io.IOException: Cannot run program "/bin/ls": error=13, Permission denied Commented Mar 26, 2020 at 2:04
  • Try String cmd= "ls -l"; Commented Mar 26, 2020 at 2:07
  • java.io.IOException: Cannot run program "ls": error=13, Permission denied Commented Mar 26, 2020 at 2:08
  • Run the terminal from the folder where jar is present. To give all the permissions (read, write & execute) -> chmod -R 777 /folder. Then execute the jar Commented Mar 26, 2020 at 2:10

1 Answer 1

2

I hope you are familiar with vi. If not, ignore the 3rd command given below and just copy Main.java file to /Users/your-user-directory/

cd ~
pwd
vi Main.java
javac Main.java
java Main

Main.java

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

public class Main {
    public static void main(String[] args) {
        String s;
        Process p;
        String cmd = "ls";

        try {
            Runtime run = Runtime.getRuntime();
            p = run.exec(cmd);
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

            while ((s = br.readLine()) != null) {
                System.out.println("line: " + s);
            }

            p.waitFor();
            System.out.println("exit: " + p.exitValue());
            p.destroy();

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.