2011-06-14 15 views
4

我想用java.nio.channels.FileChannel從文件中讀取,但我想像BufferedReader#readLine()那樣每行讀取一行。我需要使用java.nio.channels.FileChannel而不是java.io的原因是我需要對文件進行鎖定,並從該鎖定文件逐行讀取。所以我強迫使用java.nio.channels.FileChannel。請幫助如何使用java.nio.channels.FileChannel讀取ByteBuffer實現像BufferedReader一樣的行爲#readLine()

編輯這裏是我的代碼試圖用的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();,它馬上去finallylock仍然null,所以lock.release()生成NullPointerException。我不知道爲什麼。

回答

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。

+0

我嘗試了一下,出於某種原因,當我嘗試用FileInputStream鎖定文件時,它不能正常工作。不知道爲什麼, – 2011-06-14 15:54:00

+0

我記得我以前用過這個,沒有任何問題..你可以告訴我什麼是工作 – 2011-06-14 15:55:22

+0

@Suraj:我有更新我的文章,我的代碼使用'FileInputStream',你可以看看嗎? – 2011-06-14 16:01:40

相關問題