In this tutorial you will learn about searching file and open it for edit in java
List All Files And Direcories In A Direcoty
In the application given below you will listFiles() method is used to list all the file and direcories in the given directories. This method returns the ArrayList of File object
We have used isFile() and isDirectory() methods of File class that returns the boolean value. It is generally used befor any operation on file or dirctory.
Please consider the example given below
SearchFileAndDirectories.java
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; public class SearchFileAndDirectories { public static void main(String[] args) { String path = ""; System.out.println("Please Enter the path"); try { BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); path = br.readLine(); } catch (IOException e) { e.printStackTrace(); } String fileName, directoryName; File searchInDirectory = new File(path); File[] listOfFiles = searchInDirectory.listFiles(); File[] listOfDirectories = searchInDirectory.listFiles(); System.out.println("********************************************"); System.out.println("List Of All File in " + path); System.out.println("********************************************\n"); for (File file : listOfFiles) { if (file.isFile()) { fileName = file.getName(); System.out.println(fileName); } } System.out.println("********************************************"); System.out.println("List Of All Directory in " + path); System.out.println("********************************************\n"); for (File file : listOfFiles) { if (file.isDirectory()) { fileName = file.getName(); System.out.println(fileName); } } } }
When you run this application it will display message as shown below:
Please Enter the path C:\Java\jdk1.6.0_14 ******************************************** List Of All File in C:\Java\jdk1.6.0_14 ******************************************** COPYRIGHT LICENSE LICENSE.rtf README.html README_ja.html README_zh_CN.html register.html register_ja.html register_zh_CN.html src.zip THIRDPARTYLICENSEREADME.txt ******************************************** List Of All Directory in C:\Java\jdk1.6.0_14 ******************************************** bin demo include jre lib sample |
[ 0 ] Comments