Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search a file?

Tags:

java

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: ");
like image 673
Angela Vinagrera Avatar asked Feb 11 '23 22:02

Angela Vinagrera


2 Answers

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.

like image 70
codebot Avatar answered Feb 23 '23 10:02

codebot


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");
}
like image 28
Madhawa Priyashantha Avatar answered Feb 23 '23 10:02

Madhawa Priyashantha