0

i created a file and when i run the program, the data is been written in to the file but when i run the program again the new data over write on old data. i need once the program is running and gathers data, these data are writable into the file in cascade next each other without overwriting on previous data in file.

this code running successful but when i run the program again the over writing happens which i don need that, i need to save previous data in side the file and write the new data next it and soon.

public class MainActivity extends Activity {
File file;
String sdCard;
FileOutputStream fos;
OutputStreamWriter myOutWriter;
String FlieName = "Output1.txt";
EditText txtData;
Button btnWriteSDFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtData = (EditText) findViewById(R.id.editText1);
    btnWriteSDFile = (Button) findViewById(R.id.button1);
    btnWriteSDFile.setOnClickListener(new OnClickListener() 
    {
        public void onClick(View v)
        { 
            try {
                file = new File("/sdcard/Output1.txt");
                file.createNewFile();
                fos = new FileOutputStream(file);

                String eol = System.getProperty("line.separator");
                myOutWriter =new OutputStreamWriter(fos);
                myOutWriter.append(txtData.getText() + eol);// write from editor 
                myOutWriter.close();
                fos.close();
                Toast.makeText(v.getContext(),"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT).show();
                txtData.setText("");
            } catch (Exception e) {
                // e.printStackTrace();
                Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
            }
        }
    });

}

}

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
Mohsen Ali
  • 655
  • 1
  • 9
  • 30

2 Answers2

3

First, you are calling createNewFile(). This indicates that you want to create a new file. If you do not want to create a new file, do not call createNewFile(). And, since the documentation for createNewFile() says "This method is not generally useful", you may wish to consider just getting rid of it.

Second, you need to indicate that you want to append to the existing data when you open and use that file. The standard recipe for this:

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //oh noes!
}

The true in the second parameter to the FileWriter constructor indicates that you want to append instead of overwrite.

Third, do not hardcode paths in Android. /sdcard/Output1.txt has been poor form for years and will not work on some Android devices.

Fourth, do not clutter up the root of external storage. Hence, instead of:

file = new File("/sdcard/Output1.txt");

use:

file = new File(getExtenalFilesDir(null), "Output1.txt");

to put the file in a subdirectory unique for your own app.

Community
  • 1
  • 1
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

Try using java.nio.Files along with java.nio.file.StandardOpenOption

try(BufferedWriter bufWriter =
        Files.newBufferedWriter(Paths.get("/sdcard/Output1.txt"),
            Charset.forName("UTF8"),
            StandardOpenOption.WRITE, 
            StandardOpenOption.APPEND,
            StandardOpenOption.CREATE);
    PrintWriter printWriter = new PrintWriter(bufWriter, true);)
{ 

    printWriter.println("Text to be appended.");

}catch(Exception e){
    //Oh no!
}

This uses a try-with-resources statement to create a BufferedWriter using Files, which accepts StandardOpenOption parameters, and an auto-flushing PrintWriter from the resultant BufferedWriter. PrintWriter's println() method, can then be called to write to the file.

The StandardOpenOption parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist.

Paths.get("path here") can be replaced with new File("path here").toPath(). And Charset.forName("charset name") can be modified to accommodate the desired Charset.

icasdri
  • 106
  • 1
  • 4
  • OutputStream fos = Files.newOutputStream(Paths.get("/sdcard/Output1.txt"), StandardOpenOption.WRITE, //Open the file for writing StandardOpenOption.APPEND, //If the file is opened for writing, append to it StandardOpenOption.CREATE); //Create the file if it does not exist – Mohsen Ali Jul 24 '13 at 03:32
  • @Mohsen Ali, thanks for pointing out the errors. Fixed the variable mishap, and uncaught exception. Also using a try-with-resources, and PrintStream, as it is more suitable for this purpose. – icasdri Jul 25 '13 at 17:11
  • After further research, concluded that PrintWriter is the more preferred way for writing Strings and Chars to streams, as opposed to PrintStream. – icasdri Jul 25 '13 at 20:00