Saturday, 14 November 2015

Java program which can list all files in a given directory

 With this code you can list all files in a given directory:

package in.blogspot.java2bigdata;

import java.io.File;
 
public class ListFiles 
{
 
 public static void main(String[] args) 
{
   // Directory path here
  String path = "."; 
 
  String files;
  File folder = new File(path);
  File[] listOfFiles = folder.listFiles(); 
 
  for (int i = 0; i < listOfFiles.length; i++) 
  {
    if (listOfFiles[i].isFile()) 
   {
   files = listOfFiles[i].getName();
   System.out.println(files);
      }
  }
}
}

If you want to list only .txt files for example, Use this code:

package in.blogspot.java2bigdata;

import java.io.File;
 
public class ListTxtFiles 
{
 
 public static void main(String[] args) 
{
 
  // Directory path here
  String path = "."; 
 
  String files;
  File folder = new File(path);
  File[] listOfFiles = folder.listFiles(); 
 
  for (int i = 0; i < listOfFiles.length; i++) 
  {
 
   if (listOfFiles[i].isFile()) 
   {
   files = listOfFiles[i].getName();
       if (files.endsWith(".txt") || files.endsWith(".TXT"))
       {
          System.out.println(files);
        }
     }
  }
}
}

You can modify the .txt or .TXT to be whatever file extension you wish.

1 comment: