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。我不确定为什么。

4

1 回答 1

1

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

于 2011-06-14T15:51:04.410 回答