Search files by text content inside

瘦欲@ 提交于 2019-12-06 19:12:27

Iterating over the files

If you are on Java7 use the Files.walkFileTree(args) to walk the tree: doc

If you are on Java below version 7 just use File.listFiles() recursively.

Finding in a file

Use Scanner.findWithinHorizon(String pattern, int horizon) to find whatever regexp you want: doc

Here is an example of how you could do it:

private List<String> searchFiles(File file, String pattern, List<String> result) throws FileNotFoundException {

    if (!file.isDirectory()) {
        throw new IllegalArgumentException("file has to be a directory");
    }

    if (result == null) {
        result = new ArrayList<String>();
    }

    File[] files = file.listFiles();

    if (files != null) {
        for (File currentFile : files) {
            if (currentFile.isDirectory()) {
                searchFiles(currentFile, pattern, result);
            } else {
                Scanner scanner = new Scanner(currentFile);
                if (scanner.findWithinHorizon(pattern, 0) != null) {
                    result.add(currentFile.getName());
                }
                scanner.close();
            }
        }
    }
    return result;
}

you could use the method in your code like this:

 File folder = selectedFile.isDirectory() ? selectedFile : currentDirectory;
 ArrayList<String> files = new ArrayList<String>();
 try {
    files = searchFiles(folder, "Hello", files);
 } catch (FileNotFoundException e1) {
    // you should tell the user here that something went wrong
 }
 // 'files' now contains the resulting file names 

Here is an example in java 8 thats streams not recursive

try( Stream<Path> walk = Files.walk( Paths.get( SRC ) ) ) {
        final String regex = "someregex";
        List<String> filesContainingRegex = walk.filter( path -> !Files.isDirectory( path ) ).flatMap( path -> {
            try {
                File file = path.toFile();
                Scanner scanner = new Scanner( file );
                if( scanner.findWithinHorizon( regex, 0 ) != null ) {
                    scanner.close();
                    return Stream.of( path.getFileName().toString() );
                }
                scanner.close();
            } catch( FileNotFoundException fnfe ) {
                System.out.println( fnfe.getMessage();
            }
            return Stream.empty();
        } ).collect( Collectors.toList() );
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!