Supposedly the user will enter their "ID #: 1203103" then after that it will automatically create a text file named 1203103.txt. How can I search the file name "1203103.txt" in the file directory?
String id = scan.nextLine();
File file = new File(id+".txt");
FileWriter fileWrite = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWrite);
System.out.println("Enter the ID # to search: ");
You can try with this.
import java.io.*;
class Main {
public static void main(String[] args) {
File dir = new File("C:"); //file directory
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("1203103"); //here is you file name starts with. Or you can use name.equals("1203103.txt");
}
};
String[] children = dir.list(filter);
if (children == null) {
System.out.println("Either dir does not exist or is not a directory");
}else {
for (int i=0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
Hope this helps.
Scanner scan=new Scanner(System.in);
System.out.println("Enter the ID # to search: ")
String id=scan.next();
File f= new File(id+".txt");
if(f.exists() && !f.isDirectory()) {
System.out.println("file exist");
}else{
System.out.println("file doesn't exist");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With