0

How to append data one by one in existing file? Am using following code.. Append the data row order in file..How to solve this?

    private String SaveText() {

    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File (sdCard.getAbsolutePath()+File.separator+"GPS");
    dir.mkdirs();

    String fname =  "gps.txt";
    File file = new File (dir, fname);

   FileOutputStream fos;
    try {

        fos = new FileOutputStream(file,true);
        OutputStreamWriter out=new OutputStreamWriter(fos);
        out.write(value1);
        out.close();
        fos.close();

        Toast.makeText(getApplicationContext(), "Saved lat,long", Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return dir.getAbsolutePath();
}
comrade
  • 4,590
  • 5
  • 33
  • 48
Mani
  • 71
  • 1
  • 7

3 Answers3

0

Try this code

    try{

        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file,true), "UTF-8");
        BufferedWriter fbw = new BufferedWriter(writer);
        fbw.write(value1);
        fbw.newLine();
        fbw.close();
       Toast.makeText(getApplicationContext(), "Saved lat,long", Toast.LENGTH_SHORT).show();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
sasikumar
  • 12,540
  • 3
  • 28
  • 48
0

Copy and paste this code.

public void SaveText(String sFileName, String sBody){
try
{
    File root = new File(Environment.getExternalStorageDirectory(), "Notes");
    if (!root.exists()) {
        root.mkdirs();
    }
    File gpxfile = new File(root, sFileName);
    FileWriter writer = new FileWriter(gpxfile);
    writer.append(sBody);
    writer.flush();
    writer.close();
    Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
     e.printStackTrace();
     importError = e.getMessage();
     iError();
}}
SerhatSs
  • 61
  • 4
-1

In JAVA 7 you can try:

       try {

             Files.write(Paths.get(dir+File.separator+fname), latLng.getBytes(), StandardOpenOption.APPEND);

            } catch (IOException e) {
                e.printStackTrace();
           }

checkout Beautiful explanation :here

Community
  • 1
  • 1
Rustam
  • 6,485
  • 1
  • 25
  • 25