Runtime.getRuntime().exec("ls ~") does not list the contents of home directory

1.5k views Asked by At

this is a Linux machine and the following code does not result in any output, I am curious why. P.S. - I didn't read about tilde needing to be escaped but in any case escaped tilde with a backslash and javac pointed out the syntax error.

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

class Run {
    public static void main(String args[]) throws IOException {
        Process p = Runtime.getRuntime().exec("ls ~");
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}
2

There are 2 answers

0
Chai T. Rex On

That's because ~ is replaced with the path to your home directory by the shell. You aren't using the shell. Instead, it's like you ran ls '~', which gives the error:

ls: cannot access '~': No such file or directory

In fact, you can see just that happen when you change p.getInputStream() to p.getErrorStream(), which makes your program output:

ls: cannot access '~': No such file or directory
0
Elliott Frisch On

You need ~ interpolated by the shell to get the home folder, instead you can read the user.home from system properties like

Process p = Runtime.getRuntime().exec("ls " + System.getProperty("user.home"));

You could also do it with a ProcessBuilder like

ProcessBuilder pb = new ProcessBuilder("ls", System.getProperty("user.home"));
pb.inheritIO();
try {
    pb.start().waitFor();
} catch (InterruptedException e) {
    e.printStackTrace();
}