user3922757
user3922757

Reputation: 305

How to search for files in directory that start with String

I have a directory full of text files. The naming convention of these files is {userName} + {dayOfYear}

SuperMan201
JamesBond056
JamesBond101
JamesBond093
JamesBondImposter004
SuperMan051
JamesBond057
JamesBond004

I want to search through my files for files that start with Jamesbond. How can I get the first instance of a text file that starts with Jamesbond and not get JamesBondImposter matching my search.

I have a LinkedHashSet that stores the usernames of the users that have text files in the directory. Essentially I want to get the first instance of a JamesBond text file read the file,move the file to another directory, then read subsequent files if they exist; and then move on to the next username in the LinkedList.

Upvotes: 0

Views: 133

Answers (3)

VGR
VGR

Reputation: 44355

If you're using Java 8, you can do this:

Path dir = Paths.get(fullPathOfDirectory);

Stream<Path> jamesBondFiles = Files.list(dir).filter(path ->
    path.getFileName().toString().matches("JamesBond\\d+"));

Iterator<Path> i = jamesBondFiles.iterator();
while (i.hasNext()) {
    Path file = i.next();
    try (BufferedReader reader = Files.newBufferedReader(file)) {
        // Read and process file
    }
}

If you're using Java 7, or don't want to use a Stream, you can do:

Path dir = Paths.get(fullPathOfDirectory);

final PathMatcher matcher =
    dir.getFileSystem().getPathMatcher("regex:JamesBond\\d+");

DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
    @Override
    public boolean accept(Path path) {
        return matcher.matches(path.getFileName());
    }
};

try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, filter)) {
    Charset charset = Charset.defaultCharset();
    for (Path file : ds) {
        try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
            // Read and process file
        }
    }
}

Upvotes: 0

Ramzan Zafar
Ramzan Zafar

Reputation: 1600

Using Apache commons-io (listFiles and iterateFiles methods). Usually the code looks something like this:

File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("James*");
File[] files = dir.listFiles(fileFilter);

if(files!=null && files.length > 0)
{

 your desired file is files[0]
}

Upvotes: 1

Nadir
Nadir

Reputation: 1379

If you want to select files from directory take a look at https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FileFilter) and https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FilenameFilter) - just write the filter that will match what you want

Upvotes: 2

Related Questions