我想用来java.nio.channels.FileChannel
从文件中读取,但我想像每行一样读取行BufferedReader#readLine()
。我需要使用java.nio.channels.FileChannel
而不是java.io
因为我需要在文件上加锁,并从该锁文件中逐行读取。所以我被迫使用java.nio.channels.FileChannel
. 请帮忙
编辑这是我尝试使用 FileInputStream 获取 FileChannel 的代码
public static void main(String[] args){
File file = new File("C:\\dev\\harry\\data.txt");
FileInputStream inputStream = null;
BufferedReader bufferedReader = null;
FileChannel channel = null;
FileLock lock = null;
try{
inputStream = new FileInputStream(file);
channel = inputStream.getChannel();
lock = channel.lock();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String data;
while((data = bufferedReader.readLine()) != null){
System.out.println(data);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
lock.release();
channel.close();
if(bufferedReader != null) bufferedReader.close();
if(inputStream != null) inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
当代码在这里时lock = channel.lock();
,它立即转到finally
并且lock
仍然是null
,所以lock.release()
生成NullPointerException
。我不确定为什么。