1

with the below piece of code, I'm able to create a new file called output.txt and i'm able to write data. Problem is this file gets recreated once i close my app and then open my app again. As because i create this in onCreate().

But i would like to have the file created only once and then i would like to append the data there after.

private File outputFile = null; FileOutputStream fOut = null; OutputStreamWriter osw = null; @Override public void onCreate(Bundle savedInstanceState) { .... if(outputFile == null) outputFile = new File("/storage/new/output.txt"); if(osr==null){ try { osr = new FileOutputStream(outputFile); out = new DataOutputStream(osr); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ..... try { out.writeBytes(data); out.flush(); //out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

2 Answers 2

5

Try setting the append flag to true when constructing your FileOutputStream

osr = new FileOutputStream(outputFile, true); 
Sign up to request clarification or add additional context in comments.

Comments

1

Try,

FileOutputStream fileOut = openFileOutput(outputFile, MODE_APPEND); OutputStreamWriter osw = new OutputStreamWriter(fileOut); osw.writeBytes(data); osw.flush(); 

2 Comments

04-20 21:46:58.750: ERROR/AndroidRuntime(31169): java.lang.IllegalArgumentException: File /storage/new/output.txt contains a path separator .........On trying i get a crash in openFileOutput . This is because my outputFile is like "/storage/new/output.txt" , but the function openFileOutput Doesnt take path separators .
You can probably do something like: File dir = new File (sdcard.getAbsolutePath() + "/where/you/want/it"); dir.mkdirs(); File file = new File(dir, "output.txt"); FileOutputStream f = new FileOutputStream(file);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.