[英]Listing files in Java without using java.io
如何在不使用java.io. *的情況下列出當前目錄中的文件和目錄?
這實際上是可行的,無需編寫任何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();
}
}
}
令人驚訝的是一個小小的想法和無聊會做什么(並且無法跳到倉促的結論(哪里有意志,有辦法))。
您可能也可以使用ClassLoader,通過覆蓋它,在某些時候Java必須迭代類路徑中的所有文件,通過掛鈎,您可以打印出它嘗試加載的所有文件,而不使用任何類型java.io. *。
經過一些調查后,我認為這不可能很容易,當然不是為了完成家庭作業,除非它是某種RE'ing任務或取證任務。
您可以使用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);
感謝@Geo的Windows命令。
您可以使用JNA對底層操作系統進行本機調用。
作為努力工作,這可能是值得的。
另一種選擇是在C中編寫OS特定代碼並通過JNI訪問它。 但是又一次。 你為什么要這個?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.