我想使用
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.我不知道为什么.