2013-06-19 52 views
0

應用程序不斷記錄傳感器數據,並將它們寫入位於手機SD卡中的.txt文件中。在寫入數據時一切都很好。未能將最後一行添加到.txt文件中 - Android

我有一個停止按鈕。一旦按下按鈕,錄製將結束,最後一行將被添加到文件的最後。

但我總是無法追加最後一行。

我調試了很長時間。代碼確實運行了最後一行追加的命令,然後關閉所有編寫器。

請幫忙!

 // stop button 
     stopButton = (Button) findViewById(R.id.button6); 
     stopButton.setOnClickListener(new OnClickListener() { 
      public void onClick(View v) { 

       // intend to append the final line 
       myPrintWriter.flush(); 
       myPrintWriter.write("This is the final line"); 

       try { 
        myOutWriter.flush(); 
        myOutWriter.close(); 
        } catch (IOException e) { 
        e.printStackTrace(); 
        } catch (NullPointerException e) { 
        e.printStackTrace(); 
       } 
      try { 
        fOut.flush(); 
        fOut.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } catch (NullPointerException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 

回答

0

整個代碼可以簡化爲下面(具有適當的嘗試捕獲)。其餘是不必要的。

// intend to append the final line 
myPrintWriter.write("This is the final line"); 
myPrintWriter.flush(); 
myPrintWriter.close(); 

調用關閉printwriter關閉潛在的作家。

+0

事實上,我甚至覺得沖洗是多餘的接近應該叫齊平。 –

+0

這能解決我的問題嗎?其實,我對PrintWriter,BufferedWriter,FileWriter感到困惑。如果你能幫助解釋不同之處,我會很感激。 –

+0

FileWriter是一個OutputStreamWriter,它基本上意味着它在編寫器(允許您處理字符串和字符流)和輸出流(以字節爲單位)之間架起一座橋樑。沒有緩衝,寫入文件是IO操作,可能會很昂貴,所以您希望減少寫入文件的次數。 BufferedWriter這樣做是因爲它基本上可以將內存緩衝區添加到底層寫入程序的所有寫入操作中,並且只在緩衝區已滿或調用flush時寫入底層寫入程序,從而減少對文件的寫入操作次數。 –

0

添加以下,而不是你一個,

myPrintWriter.append("This is the final line"); 
myPrintWriter.close(); 
相關問題