We are moved to new domain
Click -> www.ehowtonow.com
Monday, 22 May 2017

How to retrieve all the files from Directory using Java File.listFiles()

File[] java.io.File.listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of File objects is returned, one for each file or directory in the directory. Pathnames denoting the directory itself and the directory's parent directory are not included in the result. Each resulting abstract pathname is constructed from this abstract pathname using the File(File, String) constructor. Therefore if this pathname is absolute then each resulting pathname is absolute; if this pathname is relative then each resulting pathname will be relative to the same directory.

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

Note that the java.nio.file.Files class defines the newDirectoryStream method to open a directory and iterate over the names of the files in the directory. This may use less resources when working with very large directories.

Returns:
An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(String) method denies read access to the directory
Since:
1.2

ShowFiles.java
package com.javatutorialcorner.regex;

import java.io.File;

public class ShowFiles {

 private static final String DIRECOTORY_PATH = "C:\\JTC";
 static String name = "";

 public static void main(String args[]) {
  File directory = new File(DIRECOTORY_PATH);
  retrieveFiles(directory);
 }

 private static void retrieveFiles(File directory) {

  for (final File file : directory.listFiles()) {
   if (file.isDirectory()) {
    retrieveFiles(file);
   } else {
    if (file.isFile()) {
 

     System.out.println("File : " + directory.getAbsolutePath()
       + "\\" + file.getName());
    }
   }
  }
 }
}

Output
File : C:\JTC\Java\Example\example.txt
File : C:\JTC\Java\java.txt
File : C:\JTC\test.txt


Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to retrieve all the files from Directory using Java File.listFiles() Rating: 5 Reviewed By: eHowToNow