简体   繁体   中英

Read file using Java nio files walk()

I am using stream API to read files I am calling readFile() method while iterating loop in first loop I am getting path value how to remove that path value because of that I am facing array index out of bound exception. file naming converstion is "FileName_17072018".

public class RemoveCVVFilesjob {

    public static void main(String[] args) throws IOException {
        List<String> fileList;
        fileList = readFile();

        for (String str : fileList) {
            String[] strArr = str.split("_");
            System.out.println(strArr[1]);
        }
    }

    private static List<String> readFile() throws IOException {

        try (Stream<Path> paths = Files.walk(Paths.get("D:\\Projects\\Wallet\\CVVFiles"))) {

            List<String> list = paths.map(path -> Files.isDirectory(path) ? 
                path.getFileName().toString() + '/' : 
                path.getFileName().toString()).collect(Collectors.toList()
            );
            return list;
        }
    }

Your split() is correct but your map() in the stream seems to be incorrect as you collect both directories and files.
So you didn't collect the expected values : that is String with the XXX_XXX pattern.

Note that map() is not designed to filter but to transform.
Use filter() instead of and use it to filter only files :

List<String> list = paths.filter(Files::isRegularFile)
                         .map(p -> p.getFileName()
                                    .toString())
                         .collect(Collectors.toList());

The problem is that not only the files but the directory itself gets into the Stream. Example:

D:\Projects\Wallet\CVVFiles
D:\Projects\Wallet\CVVFiles\FileName_17072018.txt
D:\Projects\Wallet\CVVFiles\FileName_18072018.txt

Without filter, the mapped result is:

[CVVFiles, FileName_17072018.txt, FileName_18072018.txt]

Then it fails on getting the second element of an array of the split result by the delimiter _ on the first item, which is the directory. Filter the directory out in order to make it work:

List<String> list = paths
    .filter(Files::isRegularFile)
    .map(path -> path.getFileName().toString())
    .collect(Collectors.toList());

You might find interesting paths.peek(System.out::println).map... to find out what is getting into the map pipeline.


I suggest you use Files::isRegularFile which is exactly the same like !isSymbolicLink() && !isDirectory() && !isOther(); .

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