开发者

Program to get all files within a directory in Java

开发者 https://www.devze.com 2023-01-09 08:02 出处:网络
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

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.

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 开发者_JAVA技巧{ 
            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();  
        }       
    } 
}


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

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

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


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


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消