userimage
Moe

how to search files in my system using java api

i am using java 7 and i want to know the best way to search a file in my system. i go through many website but didn"t get any complete example for this. Can anybody give a complete example of searching a file in my file system
userimage

You can use below example which i have used in my dummy project:

package com.test.java.nio;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class FileSearch {

    public static class SearchFileVisitor extends SimpleFileVisitor<Path> {

        private final PathMatcher pathMatcher;
        private int matchCount = 0;

        SearchFileVisitor(String globPattern) {
            pathMatcher = FileSystems.getDefault().getPathMatcher(
                    "glob:" + globPattern);
        }

        @Override
        public FileVisitResult visitFile(Path filePath,
                BasicFileAttributes basicFileAttrib) {
            if (pathMatcher.matches(filePath.getFileName())) {
                matchCount++;
                System.out.println(filePath);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path directoryPath,
                BasicFileAttributes basicFileAttrib) {
            if (pathMatcher.matches(directoryPath.getFileName())) {
                matchCount++;
                System.out.println(directoryPath);
            }
            return FileVisitResult.CONTINUE;
        }

        public int getMatchCount() {
            return matchCount;
        }
    }

    public static void main(String[] args) throws IOException {

        Path rootPath = Paths.get(".");
        String globPattern = "*.txt";

        SearchFileVisitor searchFileVisitor = new SearchFileVisitor(globPattern);
        Files.walkFileTree(rootPath, searchFileVisitor);
        System.out.println("Match Count: " + searchFileVisitor.getMatchCount());
    }
}

Example Output

.abinab.txt
.testabinab1.txt
.testabinab2.txt
.xyzabinab.txt
.testabinab1.txt
.testabinab4.txt
Match Count: 3



Hope this will help you...


Answer is