Minp
Minp

Reputation: 98

How to get files with a filename starting with a certain letter?

I wrote some code to read a text file from C drive directly given a path.

String fileName1 = "c:\\M2011001582.TXT";
BufferedReader is = new BufferedReader(new FileReader(fileName1));

I want to get a list of files whose filename starts with M. How can I achieve this?

Upvotes: 0

Views: 17001

Answers (3)

DNA
DNA

Reputation: 42597

"but how can i write a code that file is exist in local drive or not"

To scan a directory for files matching a condition:

import java.io.File;
import java.io.FilenameFilter;

public class DirScan
{
    public static void main(String[] args)
    {
        File root = new File("C:\\");
        FilenameFilter beginswithm = new FilenameFilter()
        {
         public boolean accept(File directory, String filename) {
              return filename.startsWith("M");
          }
        };

        File[] files = root.listFiles(beginswithm);
        for (File f: files)
        {
            System.out.println(f);
        }
    }
}

(The files will exist, otherwise they wouldn't be found).

Upvotes: 11

To check if file exist, you can check in File Class docs In Nutshell:

File f = new File(fileName1);
if(f.exists()) {
    //do something                  
}

Upvotes: 0

Rocky
Rocky

Reputation: 951

You can split the string based on the token '\' and take the second element in the array and check it by using the startsWith() method avaialble on the String object

String splitString = fileName1.split("\\") ;
//check if splitString is not null and size is greater than 1 and then do the following

if(splitString[1].startsWith("M")){
// do whatever you want
}

Upvotes: 0

Related Questions