List of files in Java without using java.io

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

+2


source to share


4 answers


It is indeed possible without the need to write 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 (and the inability to jump to conclusions will do (where there is will, there is a way)).



Perhaps you could also do it with ClassLoader, overriding it, at some point Java has to iterate over all files in the classpath, by connecting at this point you can print all the files it tries to load without using any either java.io. *.

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

+10


source


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 Windows commands.

+7


source


You can use JNA to make your own calls to the underlying OS.

As an exercise in hard work, it can be worth the time.

+1


source


Another option is to write the OS code in C and get it via JNI . But one more time. Why do you need this?

+1


source







All Articles