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

| 我想使用“ 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。     

要回复问题请先登录注册