How to read all files in a folder in Java?
#1 building
import java.io.File; public class ReadFilesFromFolder { public static File folder = new File("C:/Documents and Settings/My Documents/Downloads"); static String temp = ""; public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Reading files under the folder "+ folder.getAbsolutePath()); listFilesForFolder(folder); } public static void listFilesForFolder(final File folder) { for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { // System.out.println("Reading files under the folder "+folder.getAbsolutePath()); listFilesForFolder(fileEntry); } else { if (fileEntry.isFile()) { temp = fileEntry.getName(); if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("txt")) System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName()); } } } } }
#2 building
To prevent the listFiles() function from Nullpointerexceptions and recursively get all files from subdirectories.
public void listFilesForFolder(final File folder,List<File> fileList) { File[] filesInFolder = folder.listFiles(); if (filesInFolder != null) { for (final File fileEntry : filesInFolder) { if (fileEntry.isDirectory()) { listFilesForFolder(fileEntry,fileList); } else { fileList.add(fileEntry); } } } } List<File> fileList = new List<File>(); final File folder = new File("/home/you/Desktop"); listFilesForFolder(folder);
#3 building
If you need more options, you can use this feature, which is designed to fill in an array list of files that exist in the folder. Options include: recursion and matching patterns.
public static ArrayList<File> listFilesForFolder(final File folder, final boolean recursivity, final String patternFileFilter) { // Inputs boolean filteredFile = false; // Ouput final ArrayList<File> output = new ArrayList<File> (); // Foreach elements for (final File fileEntry : folder.listFiles()) { // If this element is a directory, do it recursivly if (fileEntry.isDirectory()) { if (recursivity) { output.addAll(listFilesForFolder(fileEntry, recursivity, patternFileFilter)); } } else { // If there is no pattern, the file is correct if (patternFileFilter.length() == 0) { filteredFile = true; } // Otherwise we need to filter by pattern else { filteredFile = Pattern.matches(patternFileFilter, fileEntry.getName()); } // If the file has a name which match with the pattern, then add it to the list if (filteredFile) { output.add(fileEntry); } } } return output; }
Best, Adrian
#4 building
private static final String ROOT_FILE_PATH="/"; File f=new File(ROOT_FILE_PATH); File[] allSubFiles=f.listFiles(); for (File file : allSubFiles) { if(file.isDirectory()) { System.out.println(file.getAbsolutePath()+" is directory"); //Steps for directory } else { System.out.println(file.getAbsolutePath()+" is file"); //steps for files } }
#5 building
In Java 7, you can now operate in this way -http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#listdir
Path dir = ...; try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path file: stream) { System.out.println(file.getFileName()); } } catch (IOException | DirectoryIteratorException x) { // IOException can never be thrown by the iteration. // In this snippet, it can only be thrown by newDirectoryStream. System.err.println(x); }
You can also create a filter and pass it to the newDirectoryStream method above
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { public boolean accept(Path file) throws IOException { try { return (Files.isRegularFile(path)); } catch (IOException x) { // Failed to determine if it's a file. System.err.println(x); return false; } } };
Other filtering examples -http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob