tags:

views:

201

answers:

4

how to list files and directories in current directory without using java.io.*?

+6  A: 

You can use Runtime.getRuntime().exec():

String[] cmdarray;
if (System.getProperty("os.name").startsWith("Windows")) {
    cmdarray = new String[] { "cmd.exe", "/c", "dir /b" };
} else { // for UNIX-like systems
    cmdarray = new String[] { "ls" };
}

Runtime.getRuntime().exec(cmdarray);

Thanks to @Geo for the Windows commands.

Hosam Aly
`dir` will work on most Linux systems, too.
furtelwart
You should modify that to use the shell directly. You won't be able to execute dir directly on Windows, since it's a shell built-in. The Runtime call should be like this : `Runtime.getRuntime().exec(new String[] {"cmd.exe","/c","dir"})`
Geo
@Geo: Thanks for the information. I edited my answer.
Hosam Aly
A: 

You could use JNA to make native calls to the underlying OS.

As an exercise in hard work it might be a worth while.

Gareth Davis
+1  A: 

Another option is writing OS specific code in C and accessing it via JNI. But once again. Why do you want this?

dz
+10  A: 

This is actually possible without having to write any JNI or make any Runtime calls.

import java.net.URL;

import sun.net.www.content.text.PlainTextInputStream;

public class NoIO {
  public static void main(String args[]) {
    NoIO n = new NoIO();
    n.doT();
  }

  public void doT() {
    try {
      //Create a URL from the user.dir (run directory)
      //Prefix with the protocol file:/
      //Users java.net
      URL u = new URL("file:/"+System.getProperty("user.dir"));

      //Get the contents of the URL (this basically prints out the directory
      //list. Uses sun.net.www.content.text
      PlainTextInputStream in = (PlainTextInputStream)u.getContent();
      //Iterate over the InputStream and print it out.
      int c;
      while ((c = in.read()) != -1) { 
        System.out.print((char) c); 
      } 
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}

It's amazing what a little thought and boredom will do (and an inability to jump to hasty conclusions (where there's a will, there's a way)).

You could probably also do it using the ClassLoader, by overriding it, at some point Java has to iterate over all the files in the classpath, by hooking at that point you can print out all the files that it tries to load without using any kind of java.io.*.

After some investigation I don't think this is possible very easily, certainly not for a homework assignment unless it's some kind of RE'ing assignment or Forensics assignment.

PintSizedCat
Wow! Fantastic! +1
Aviator
It would be great to see a ClassLoader solution as well :D
Geo