In this tutorial you will learn that how to find files using java.io.File class
Find File In A Given Directory
The program given below find the given file in a given directory and open it in notepad editor.
To open the class we have used Desktop class. The following is the code to open the file in notepad
Desktop.getDesktop().edit(file);
The complete source code is given below
FindFileInADirectory.java
import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class FindFileInADirectory {
public static void main(String[] arsg) {
String path = "", fileName = "";
try {
System.out.print("Please Enter the path-\t");
BufferedReader filePathReader = new BufferedReader(
new InputStreamReader(System.in));
path = filePathReader.readLine();
System.out.print("Please Enter file Name-\t");
BufferedReader fileNameReader = new BufferedReader(
new InputStreamReader(System.in));
fileName = fileNameReader.readLine();
File directory = new File(path);
File[] listOfFiles = directory.listFiles();
for (File file : listOfFiles) {
String name = file.getName();
if (name.equals(fileName)) {
System.out.println(name);
if(Desktop.isDesktopSupported()){
Desktop.getDesktop().edit(file);
}
return;
}
}
System.out
.println(fileName + " not found in " + path + " directory");
} catch (IOException e) {
e.printStackTrace();
}
}
}
When you run this application it will display message as shown below:
| Please Enter the path- G:\Vinay\Swing Please Enter file Name- LoginDemo.java LoginDemo.java |

[ 0 ] Comments