How to use java.nio.channels.FileChannel to read to ByteBuffer achieve similiar behavior like BufferedReader#readLine()
I want to use java.nio.channels.FileChannel
to read from a file, but I want to read line per line like BufferedReader#readLine()
does. The reason why I need to use java.nio.channels.FileChannel
instead of java.io
is because I need to put a lock on a file, and read line by line from that lock file. So I am force to use java.nio.channels.FileChannel
. Please help
EDIT Here is my code trying to use FileInputStream to get the 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;
File开发者_如何学运维Lock 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();
}
}
}
when the code is here lock = channel.lock();
, it is immediately go to the finally
and lock
is still null
, so lock.release()
generate NullPointerException
. I am not sure why.
The reason is that you need to use FileOutpuStream instead of FileInputStream. Please try this code:
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();
}
This code works fine for me.
The NUllPointerException is actually hiding the real exception i.e. NotWritableChannelException. For locking i think we need to use OutputStream instead of InputStream.
精彩评论