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

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

解决方法:

原因是您需要使用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.

上一篇:解决mariadb启动时报错Job for mariadb.service failed because.....


下一篇:NIO编程之多客户端聊天系统