问题描述
|
我想使用“ 0”来读取文件,但是我想像“ 1”一样逐行读取。之所以需要使用“ 0”而不是“ 3”,是因为我需要在文件上放置一个锁,并从该锁文件中逐行读取。所以我被迫使用to0ѭ。请帮忙
编辑这是我的代码尝试使用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
。我不知道为什么。
解决方法
原因是您需要使用FileOutpuStream而不是FileInputStream。
请尝试以下代码:
FileOutputStream outStream = null;
BufferedWriter bufWriter = null;
FileChannel channel = null;
FileLock lock = null;
try{
outStream = new FileOutputStream(file);
channel = outStream.getChannel();
lock = channel.lock();
bufWriter = new BufferedWriter(new OutputStreamWriter(outStream));
}catch(IOException e){
e.printStackTrace();
}
这段代码对我来说很好用。
NUllPointerException实际上是隐藏真正的异常,即NotWritableChannelException。对于锁定,我认为我们需要使用OutputStream而不是InputStream。