2017-04-11 63 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

谢谢它的工作。 –