无法附加到现有的.txt文件中

时间:2017-04-11 20:41:30

标签: java android

我无法在现有的.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());
                    }

1 个答案:

答案 0 :(得分:1)

您需要以apppend模式打开文件,如下所示

更改

FileOutputStream fOut = new FileOutputStream(file);

FileOutputStream fOut = new FileOutputStream(file, true);

请参阅FileOutputStream javadoc