How can I read files into memory while walking a directory tree using Java NIO?
The following code is my first attempt:
String dirStart = "/start/directory/";
Path root = Paths.get(dirStart);
Files.walkFileTree(root.toAbsolutePath().normalize(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, java.nio.file.attribute.BasicFileAttributes attrs) throws IOException {
System.out.println(file);
String[] dirs = file.toString().split("/");
String var1 = dirs[2];String var2 = dirs[3];String var3 = dirs[4];
System.out.println("var1 is: "+var1);
System.out.println("var2 is: "+var2);
System.out.println("var3 is: "+var3);
BufferedReader bufferedReader = null;
try {
InputStream inputStream = Files.newInputStream(file);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
System.out.println("Reading Line: " + bufferedReader.readLine());
} catch (IOException e) {e.printStackTrace();
}
finally {
try {bufferedReader.close();}
catch (IOException ioe) {ioe.printStackTrace();}
}
return FileVisitResult.CONTINUE;
}
});
But the following line is throwing a null pointer error:
try {bufferedReader.close();}
Perhaps the problem might be that the code above is mixing java.nio
with java.io
, but how can I fix it?
ANSWER:
As per SotiriosDelimanolis
's suggestion, I tried nesting try-with-resources
statements, and got the following code, which solves this problem and answers this question:
Path root = Paths.get(dirStart);
Files.walkFileTree(root.toAbsolutePath().normalize(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, java.nio.file.attribute.BasicFileAttributes attrs) throws IOException {
try(InputStream inputStream = Files.newInputStream(file);BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))){
System.out.println("Reading Line: " + bufferedReader.readLine());
} catch (IOException e) {e.printStackTrace();}
return FileVisitResult.CONTINUE;
}
});