0

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

Dar56
  • 125
  • 1
  • 1
  • 5

5 Answers5

3
  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.
MByD
  • 135,866
  • 28
  • 264
  • 277
  • Thanks alot. This basically solved my problem. Lesson learned.. About (3), how do I handle an error stream? With a try/catch or ? – Dar56 Apr 25 '11 at 22:26
  • See also this Java implementation of [ls -R](http://stackoverflow.com/questions/2007071/nix-ls-command-in-java/2009376#2009376) – trashgod Apr 25 '11 at 22:29
  • @Dar56 - You can get the error stream almost in the same way you got the input stream - `child.getErrorStream()`. – MByD Apr 25 '11 at 22:37
  • @MByD Any particular reason you suggested `System.out.println(e.toString())` instead of `e.printStackTrace()`? It's better than ignoring the exception, of course, but there's really no good reason to hide stack traces. – Isaac Truett Apr 25 '11 at 22:41
  • @MByD Thank you. You hit on a pet peeve of mine. :) – Isaac Truett Apr 25 '11 at 22:45
1

The best way is to use commons exec http://commons.apache.org/exec/

This has things that catch quirks that can really drive you up the wall, such as the whole process blocking if you didn't clear its output stream, escaping quotes in commands, etc.

Here is a method that will run the del command in windows successfully. Note the use of cmd since del is not a standalone executable:

private void deleteWithCmd(File toDelete) throws IOException {
    CommandLine cmdLine = new CommandLine("cmd.exe");
    cmdLine.addArgument("/C");
    cmdLine.addArgument("del");
    cmdLine.addArgument(toDelete.getAbsolutePath());
    DefaultExecutor executor = new DefaultExecutor();
    int exitValue = executor.execute(cmdLine);
}
bobjandal
  • 11
  • 1
0

You can also do something like that in java 6 :

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

public class ListFilesFromRegExp {

    public static void main(String[] args) throws IOException {
        File dir = new File("files/");
        File[] files = dir.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.matches("File[0-9].c");
            }
        });
        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i].getAbsolutePath());
        }
    }
}
0
  • a) What is the java console?
  • b) You should use javas File.listFiles () instead of Runtime.exec, which isn't portable, and makes Name splitting neccessary - a hard thing, for filenames which contain spaces, blanks, newlines and so on.
  • c) Whats wrong with your code?
  • d) Why don't you do anything in the case of Exception?
user unknown
  • 35,537
  • 11
  • 75
  • 121
0

Here is a more thorough example that accounts for OS versions and error conditions ( as stated by MByD above)

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4

Remember that using "exec" means that your application is no longer cross-platform and loses one of the main advantages of Java.

A better approach is to use java.io package.

http://download.oracle.com/javase/tutorial/essential/io/dirs.html

Kal
  • 24,724
  • 7
  • 65
  • 65
  • Does this mean that if my cmd = "ping www.google.com", it would not be cross platform as well? Or is it just because of the "dir" command? – Dar56 Apr 25 '11 at 22:49
  • Yes. I was specifically answering the fact that you used "dir" in your example. In general though, "exec" is running a process on the machine. This means that the command you pass it is dependent on the machine. – Kal Apr 26 '11 at 01:13
  • Ok thanks alot. I have but one more question. I have successfully used this code to get ping and dir-results, but when i try to get screen output from arpspoof, it does not give me anything back. Is there a reason for this? – Dar56 Apr 26 '11 at 12:36