0

How can I append an string into a text file? I know how to write in a text file but now I want to append using my code but it doesn't append it just writing a new string instead. Here is my code:

FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
    fOut = openFileOutput("sample.txt", Context.MODE_PRIVATE);
    osw = new OutputStreamWriter(fOut);
    osw.append("this is append text");
    osw.close();
    fOut.close();

    } catch (Exception e) {
        Toast.makeText(Ticketing.this, "Error: " + e,
                Toast.LENGTH_SHORT).show();
        e.printStackTrace(System.err);
        return;
    }

Please help! Sorry for my bad English. Thanks!

Julian Suarez
  • 4,499
  • 4
  • 24
  • 40
bernzkie
  • 1,269
  • 2
  • 16
  • 35

4 Answers4

1

Use BufferedWriter to avoid creation of new Strings.

Do something like this:

try{        
File file =new File("sample.txt");
FileWriter fW= new FileWriter(file.getName(),true);
BufferedWriter bW= new BufferedWriter(fW);
bW.write("this is append text");
bW.close();
    }
catch(Exception e)
   {Log.e("Exception: ", e + " ");}
Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110
Ankesh
  • 43
  • 5
  • i am tryng the code above but it gives me an error : `error:java.io.FileNotFoundException:/sample.text:Open Failed: EROFS:(Read-only-file system)` – bernzkie Feb 03 '15 at 10:21
0

Use this: FileWriter(File file, boolean append)

Patrick
  • 3,578
  • 5
  • 31
  • 53
0

You have to open your File withe new FileOutputStream("sample.txt", true)

From the documentation:

public FileOutputStream(File file,boolean append) throws FileNotFoundException

Creates a file output stream to write to the file represented by the specified File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection. First, if there is a security manager, its checkWrite method is called with the path represented by the file argument as its argument.

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

Parameters:file - the file to be opened for writing´.

append - if true, then bytes will be written to the end of the file rather than the beginning

Jens
  • 67,715
  • 15
  • 98
  • 113
0

mmm... try this..

FileOutputStream fOut = null;
OutputStreamWriter osw = null;
String separator = System.getProperty("line.separator");
try {
    fOut = openFileOutput("sample.txt",MODE_APPEND|MODE_WORLD_READABLE);
    osw = new OutputStreamWriter(fOut);
    osw.write("this is append text");
    osw.write(separator);
    osw.flush();
    osw.close();
} catch (Exception e) {
    Toast.makeText(Ticketing.this,"Error: " + e, Toast.LENGTH_SHORT).show();
    return;

}

Polar
  • 3,327
  • 4
  • 42
  • 77