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;
}
}
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With