簡體   English   中英

用Java獲取目錄中的所有文件的程序

[英]Program to get all files within a directory in Java

我正在研究這個程序來獲取目錄中的所有文件。 出於某種原因,我在第16行得到一個NullPointerException。我不知道為什么,因為這是一個似乎與我們的老師在課堂上工作的模板。 謝謝。

import java.util.*;
import java.io.*;

public class FindDirectories {
    public static void main(String[] args) { 
        if (args.length == 0) { 
            args = new String[] { ".." }; 
        }

        List<String> nextDir = new ArrayList<String>(); 
        nextDir.add(args[0]); // either the one file, or the directory
        try { 
            while(nextDir.size() > 0) {     // size() is num of elements in List 
                File pathName = new File(nextDir.get(0)); // gets the element at the index of the List 
                String[] fileNames = pathName.list();  // lists all files in the directory
                for(int i = 0; i < fileNames.length; i++) { 
                  File f = new File(pathName.getPath(), fileNames[i]); // getPath converts abstract path to path in String, 
                                                                    // constructor creates new File object with fileName name   
                  if (f.isDirectory()) { 
                     System.out.println(f.getCanonicalPath()); 
                     nextDir.add(f.getPath()); 
                  } 
                  else {
                      System.out.println(f);
                  }
               } 
               nextDir.remove(0); 
            } 
        } 
        catch(IOException e) { 
            e.printStackTrace();  
        }       
    } 
}

查看Javadoc for File.list() 特別:

如果此抽象路徑名不表示目錄,或者發生I / O錯誤,則返回null。

在你的代碼pathName.list(); 必須返回null,因此pathName不表示有效目錄,或者嘗試從該目錄獲取文件列表時發生IO錯誤。

使用下面的代碼片段來獲取所有子目錄中的所有文件:

import java.io.File;

/**
 *
 * @author santoshk
 */
public class ListFiles {

     File mainFolder = new File("F:\\personal");
     public static void main(String[] args)
     {
         ListFiles lf = new ListFiles();
         lf.getFiles(lf.mainFolder);
     }
     public void getFiles(File f){
         File files[];
         if(f.isFile())
             System.out.println(f.getAbsolutePath());
         else{
             files = f.listFiles();
             for (int i = 0; i < files.length; i++) {
                 getFiles(files[i]);
             }
         }
     }
}
import java.io.*;

public class filedir 
{
    public static void main(String[] args)
    {
        try{
            Files f = new File("C:\\");//the path required
            String a[];
            a=f.list(); 
            for (int i = 0; i <a.length; i++) {
               System.out.println(a[i]);
              }
        } catch(Exception e) {
            System.err.println(e);
        }
    }
}

如果您在第16行獲得NullPointerException,則必須表示fileNames為null,因此fileNames.length無效。 看一下File.list的javadoc,如果pathName不是目錄,或者發生異常,你會看到pathName.list()可以為null。 所以你只需要在嘗試使用它之前檢查fileNames是否為null。

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;


public class FileEnumerator {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        // Prepare the List of files
        String path = "C:/";
        ArrayList<String> Files = new ArrayList<String>();
        LinkedList<String> Dir = new LinkedList<String>();
        File f = new File(path);
        Dir.add(f.getAbsolutePath());
        while(!Dir.isEmpty())
        {
            f = new File(Dir.pop());
            if(f.isFile())
            {
                Files.add(f.getAbsolutePath());
            }
            else
            {
                String arr[] = f.list();
                try
                {
                for(int i = 0;i<arr.length;i++)
                {
                    Dir.add(f.getAbsolutePath()+"/"+arr[i]);
                }
                }
                catch(NullPointerException exp)
                {
                    Dir.remove(f.getAbsoluteFile());
                }
            }
        }


                //Print the files
        for(int i = 0;i<Files.size();i++)
        {
            System.out.println(Files.get(i));
        }
    }

}

我認為這段代碼應該運行良好。 雖然我在Windows上測試過它。 但其他操作系統最多只需要很小的改動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM