如何使用java.nio.channels.FileChannel读取到ByteBuffer,实现类似于BufferedReader#readLine()的行为

5
我想使用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 异常。我不确定为什么会这样。

1个回答

1
原因是您需要使用FileOutputStream而不是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进行锁定。


我尝试过,但不知为何,当我尝试使用FileInputStream锁定文件时,它并不能很好地工作。 - Thang Pham
我记得以前使用过这个,没有任何问题。你能告诉我哪里出了问题吗? - Suraj Chandran
@Suraj:我已经更新了我的帖子,使用了FileInputStream的代码,你能看一下吗? - Thang Pham
原因是你需要使用OutputStream而不是INputStream,我会更新答案。 - Suraj Chandran
但是我尝试从文件中读取,而不是写入。我不能使用OutputStream进行读取,或者我漏掉了什么? - Thang Pham
通常情况下,在修改期间会进行锁定……但无论如何,即使您想这样做,也可以使用outputstream进行锁定,然后打开inputstream并读取,然后稍后完成后释放outputstream锁定。我以前见过这种情况。 - Suraj Chandran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接