Search code examples
javahttp-redirectdirls

Outputting result of "dir" to console in Java


I want to output the result of the "dir" command to the java console. I have already looked on Google and here, but none of the examples work for me, thus making me rite this post.

My code is as follows:

try
    {
        System.out.println("Thread started..");
        String line = "";
        String cmd = "dir";

        Process child = Runtime.getRuntime().exec(cmd);

        //Read output
        BufferedReader dis = new BufferedReader( new InputStreamReader(child.getInputStream() ));

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

        dis.close();

    }catch (IOException e){

    }

What am I doing wrong?

Any help would be very nice.

Thanks in advance,

Darryl


Solution

    1. You cannot run "dir" as a process, you need to change it to String cmd = "cmd dir";.
    2. You don't handle the exception at all. adding the line e.printStackTrace()); in the catch block would tell you what I wrote in (1). Never ignore exceptions!
    3. You don't handle error stream. This might cause your program to hang, handle error stream and read from both streams (error and input) in parallel using different streams.