1

i using this function:

> private void writeToFile(String data) {
>     try {
>         OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("mywords.txt",
> Context.MODE_PRIVATE));
>         outputStreamWriter.write(data);
>         outputStreamWriter.close();
>     }
>     catch (IOException e) {
>         Log.e("Exception", "File write failed: " + e.toString());
>     }  }

i want to write a lot of times and every time i write it changes like deletes all and adds new thing i write but i do not want it to delete

husky thanks i do not know why you deleted your comment it works i changed to MODE_APPEND

another problem how do i do space in the text file

learning
  • 37
  • 7
  • read the doc for `openFileOutput`. In particular, the possible values of the parameters. – njzk2 Nov 17 '14 at 20:28
  • what space do you want to have? If you want space as a character try `data + " "`, or if you want to enter a line each time you write in file, just try `println` instead of `write`, or `data + "\r\n"` – Hana Bzh Nov 18 '14 at 05:06
  • you right im dumb i did it in wrong place for some reason tnx – learning Nov 18 '14 at 08:38

3 Answers3

2

Pass true as the second argument to FileOutputStream to open the file in append mode.

OutputStreamWriter writer = new OutputStreamWriter(
                            new FileOutputStream("mywords.txt", true), "UTF-8");
BatScream
  • 19,260
  • 4
  • 52
  • 68
0

OutputStreamWriter by default overwrites. In order to append information to a file, you will have to give it additional information in the constructor. See also OutputStreamWriter does not append for more information.

Community
  • 1
  • 1
Razz
  • 220
  • 1
  • 6
  • im new started 2weeks ago is there a diffrent code to write i just found this one never did writing – learning Nov 17 '14 at 20:05
0

Try this:

  private void writeToFile(String data) {


    File file = new File("mywords.txt");

    FileOutputStream fos = null;

    try {

        fos = new FileOutputStream(file, true);

        // Writes bytes from the specified byte array to this file output stream 
        fos.write(data.getBytes());

    }
    catch (FileNotFoundException e) {
        System.out.println("File not found" + e);
    }
    catch (IOException ioe) {
        System.out.println("Exception while writing file " + ioe);
    }
    finally {
        // close the streams using close method
        try {
            if (fos != null) {
                fos.close();
            }
        }
        catch (IOException ioe) {
            System.out.println("Error while closing stream: " + ioe);
        }

    }
  }
Hana Bzh
  • 2,212
  • 3
  • 18
  • 38