Reputation: 11201
I am trying to create a simple text file, and I am successful in doing that by the following code:
file=new File(mContext.getExternalFilesDir(null), generateFileName());
fop=new FileOutputStream(file);
timeString="Method executed in:"+formatTime(executionTime)+"secs";
contentInBytes=timeString.getBytes();
startString="start()".getBytes();
stopString="stop()".getBytes();
fop.write(startString);
fop.write(System.getProperty("line.separator").getBytes());
fop.write(contentInBytes);
fop.write(System.getProperty("line.separator").getBytes());
fop.write(stopString);
fop.flush();
fop.close();
Log.d("write","Done writing.");
When I try to append same text to it again, the old text gets cleared out resulting in an empty text file.
This is how I tried to append the text:
fOutA=new FileOutputStream(file); //I also tried: new FileOutputStream(myFile,true);
fOutA = mContext.openFileOutput(textFileName, mContext.MODE_APPEND);
timeString="Method executed in:"+formatTime(executionTime)+"secs";
contentInBytes=timeString.getBytes();
startString="start()".getBytes();
stopString="stop()".getBytes();
fOutA.write(startString);
fOutA.write(System.getProperty("line.separator").getBytes());
fOutA.write(contentInBytes);
fOutA.write(System.getProperty("line.separator").getBytes());
fOutA.write(stopString);
fOutA.flush();
fOutA.close();
Log.d("append","Done appending.");
The textfileName
param in the append code-block is same as the generatedFileName()
in write code-block.
Can someone tell me why it is happening ?
Upvotes: 0
Views: 41
Reputation: 11201
Along with the suggestion given by Rahil2952, I need to get rid of this line:
fOutA = mContext.openFileOutput(textFileName, mContext.MODE_APPEND);
I do not need the oneFileOutput
and set its mode to MODE_APPEND
. The FileOutputStream
itself appends to the existing file when append
is set to true
.
Also I do not need to use OutputStreamWriter
.
Upvotes: 0
Reputation: 2082
To write to file and append create instance of FileOutPutStream
and OutPutStreamWriter
and then use append
method of OutputStreamWriter
to append data to the file.
FileOutputStream fOut = new FileOutputStream(myFile,true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut,true);
myOutWriter.append()
Second argument means if text should be appended to the existing file or not.
Upvotes: 2