简体   繁体   中英

How to get a part of path

Hi I have a question I have function that returns me all files in List<String> there are few lines of files that ends with .pom ie the path is C://poms/xx/interested-2.0.pom how could I get just the interested because ie this is name of the pom should I use split or is there a better way to do that in Java 8 any suggestions?

public List<String> listFiles(String path, List<File> files) {

    File directory = new File(path);

    File[] fList = directory.listFiles();
    if (fList != null) {
        for (File f : fList) {
            if (f != null && f.isFile()) {
                files.add(f);
            } else if (f.isDirectory()) {
                listFiles(f.getAbsolutePath(), files);
            }
        }
    }

    return files.stream()
            .filter(file -> file.toString().endsWith(".xml"))
            .map(File::toString)
            .collect(Collectors.toList());
}

Without making too many changes to your original code you could just do :

return files.stream().filter(file -> file.toString().endsWith(".xml"))
                     .map(File::getName)
                     .map(s -> s.split("-")[0])
                     .collect(Collectors.toList());

Rather than fetching the entire path of the file, just get the name of the file.

To get file name only you can use Path.getFileName :

String fileName = Paths.get(path).getFileName(); // interested-2.0.pom
String result = fileName.split("-")[0];

Edit : You can also use listFiles(FileFilter filter) :

public List<String> listFiles(String path) {

    File directory = new File(path);
    File[] fList = directory.listFiles(p -> p.getName().endsWith(".xml"));
    if (fList != null) {
        return Arrays.stream(files)
                .map(file -> file.getName().split("-")[0])
                .collect(toList());
    }
    throw new RuntimeException("No files");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM