java 8 path filter file name

I am trying to filter files starting with "EMP" in the folder "C://Temp" and trying to return list of "Paths" i tried below code but always it is returning empty list. Is there any syntax error i am doing?

String directoryPath = "C://Temp";                            
String partOfFileName = "EMP";                           
List<Path> fileNames = Files.list(Paths.get(directoryPath))                               
                .filter(line -> line.toString().startsWith(partOfFileName))
                .map(Path::getFileName)                                    
                .collect(Collectors.toList());                             

2 answers

  • answered 2018-07-11 03:43 shmosel

    Path.toString() returns the full path representation. If you want to filter by the file name, call getFileName() within your filter operation:

    String directoryPath = "C://Temp";
    String partOfFileName = "EMP";
    List<Path> fileNames = Files.list(Paths.get(directoryPath))
            .filter(path -> path.getFileName().startsWith(partOfFileName))
            .collect(Collectors.toList());
    

  • answered 2018-07-11 03:47 Bekah Saugen

    Since you are checking the full path, you may want to check the immediate directly by using "endsWith" instead of "startsWith".

    Right now if you are in "folder1/folder2/test" and you use startsWith, it is going to check and try to filter on the first directory, "folder1".

       try {
            List<Path> fileNames = Files.list(Paths.get(directoryPath))
                    .filter(line -> line.endsWith(partOfFileName))
                    .map(Path::getFileName)
                    .collect(Collectors.toList());
    
        } catch (IOException e) {
            e.printStackTrace();
        }