2017-04-11 69 views
-1

我無法附加到現有的.txt文件中,因爲它會覆蓋寫入文件的較舊數據。請通過告訴我我錯在哪裏來幫助我。無法追加到現有的.txt文件中

這是一個與文件處理有關的類文件(Orderact.java)。

 String data="\nName- " + partyn + "; ndate- " + dt + "; product- " + prosel + "; qty- " + qty + ";"; 
        // Create the folder if required. 
        File f = new File(Environment.getExternalStorageDirectory() + "/fb"); 
        if(!f.exists()) { 
         String path = Environment.getExternalStorageDirectory() + "/fb"; 
         File folder = new File(path); 
         folder.mkdirs(); 
        } 
        String path = Environment.getExternalStorageDirectory() + "/fb"; 
        File folder = new File(path); 
        File file = new File(folder, "testing.txt"); 
        try { 
         if(!file.exists()) { 
          // Create the file. 
          file.createNewFile(); 
          FileOutputStream fOut = new FileOutputStream(file); 
          OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); 
          myOutWriter.append(data); 
          myOutWriter.close(); 
          fOut.flush(); 
          fOut.close(); 
          Toast.makeText(Orderact.this, "Saved", Toast.LENGTH_LONG).show(); 
         } else { 
          FileOutputStream fOut = new FileOutputStream(file); 
          OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); 
          myOutWriter.append(data); 
          myOutWriter.close(); 
          fOut.close(); 
          Toast.makeText(Orderact.this, "Saved", Toast.LENGTH_LONG).show(); 
         } 

        } catch (IOException e) { 
         Toast.makeText(Orderact.this, "Something went wrong.\n Not Saved", Toast.LENGTH_LONG).show(); 
         Log.e("Exception", "File write failed: " + e.toString()); 
        } 
+0

'FileOutputStream' - >閱讀該課程的文檔。 – njzk2

回答

1

你需要打開你的文件中apppend模式,如下

變化

FileOutputStream fOut = new FileOutputStream(file); 

FileOutputStream fOut = new FileOutputStream(file, true); 

請參考FileOutputStream javadoc

+0

謝謝它的工作。 –