如何使用Java NIO在目录树中读取文件到内存中?
以下代码是我的第一次尝试:
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;
}
});
但是以下行抛出空指针错误:
try {bufferedReader.close();}
也许问题可能是上面的代码混合了java.nio
和java.io
,但我该如何解决?
答案:
根据SotiriosDelimanolis
的建议,我尝试嵌套try-with-resources
语句,并获得以下代码,解决了这个问题并回答了这个问题:
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;
}
});