Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
        }
    }
like image 456
Tejal Avatar asked Jul 17 '18 10:07

Tejal


People also ask

What is files walk in Java?

Files. walk returns a stream that is lazily populated with Path by recursively walking the file tree rooted at a given starting file. The file tree is traversed depth-first. There are two overloaded Files.

What is Nio file in Java?

The java. nio. file package defines classes to access files and file systems. The API to access file and file system attributes is defined in the java.


1 Answers

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());
like image 198
davidxxx Avatar answered Oct 05 '22 02:10

davidxxx