获取Java目录中所有文件的程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3332486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:17:50  来源:igfitidea点击:

Program to get all files within a directory in Java

java

提问by Crystal

I'm working on this program to get all the files in the directory. For some reason I am getting a NullPointerException on Line 16. I don't know why though since this is a template that seemed to work in class with our teacher. Thanks.

我正在研究这个程序以获取目录中的所有文件。出于某种原因,我在第 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();  
        }       
    } 
}

采纳答案by krock

Check out the Javadoc for File.list(). Specifically:

查看Javadoc 以获取File.list(). 具体来说:

Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

如果此抽象路径名不表示目录,或者发生 I/O 错误,则返回 null。

In your code pathName.list();must be returning null so pathNamedoes not represent a valid directory, or an IO error occurred trying to get a list of files from that directory.

在您的代码中pathName.list();必须返回 null 因此pathName不代表有效目录,或者尝试从该目录获取文件列表时发生 IO 错误。

回答by Vineet

If you're getting a NullPointerException on line 16, it must mean that fileNamesis null, so fileNames.lengthis invalid. Take a look at the javadoc for File.listand you'll see that pathName.list()can be null if pathNameis not a directory, or if an exception occurs. So you'll just need to check whether fileNamesis null before trying to use it.

如果您在第 16 行收到 NullPointerException,则必须表示它fileNames为 null,因此fileNames.length无效。查看File.list 的 javadoc,pathName.list()如果pathName不是目录,或者发生异常,您将看到它可以为 null 。所以你只需要fileNames在尝试使用它之前检查它是否为空。

回答by Killer

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));
        }
    }

}

I think this code should work well. Although I have tested it just on Windows. But other OS will need at most small changes.

我认为这段代码应该运行良好。虽然我只是在 Windows 上测试过它。但是其他操作系统最多只需要很小的改动。

回答by santosh

Use bellow snippet to get all the files from all the sub directories:

使用下面的代码段从所有子目录中获取所有文件:

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]);
             }
         }
     }
}

回答by anjuna

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);
        }
    }
}