Java 实例 - 在指定目录中查找文件


以下实例演示了使用 File 类的 dir.list() 方法在指定目录中查找所有文件列表:

  1. /*
  2. author by shouce.ren
  3. Main.java
  4. */
  5.  
  6. import java.io.File;
  7.  
  8. public class Main {
  9. public static void main(String[] argv)
  10. throws Exception {
  11. File dir = new File("../java");
  12. String[] children = dir.list();
  13. if (children == null) {
  14. System.out.println("该目录不存在");
  15. }
  16. else {
  17. for (int i = 0; i < children.length; i++) {
  18. String filename = children[i];
  19. System.out.println(filename);
  20. }
  21. }
  22. }
  23. }

以上代码运行输出结果为:

  1. Car.class
  2. FileUtil.class
  3. FileUtil.java
  4. HelloWorld.class
  5. HelloWorld.java
  6. HelloWorldDebug.class
  7. HelloWorldDebug.java
  8. ……