使用Java列出文件而不使用java.io

okn*_*neo 2 java

如何在不使用java.io.*的情况下列出当前目录中的文件和目录?

Hen*_*y B 10

这实际上是可行的,无需编写任何JNI或进行任何运行时调用.

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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是一个小小的想法和无聊会做什么(并且无法跳到仓促的结论(哪里有意志,有办法)).

您可能也可以使用ClassLoader,通过覆盖它,在某些时候Java必须迭代类路径中的所有文件,通过挂钩,您可以打印出它尝试加载的所有文件,而不使用任何类型java.io.*.

经过一些调查后,我认为这不可能很容易,当然不是为了完成家庭作业,除非它是某种RE'ing任务或取证任务.

  • 看到ClassLoader解决方案也很棒:D (2认同)

Hos*_*Aly 7

你可以使用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);
Run Code Online (Sandbox Code Playgroud)

感谢@Geo的Windows命令.

  • `dir`也适用于大多数Linux系统. (4认同)