Lucas Ouwens Lucas Ouwens - 4 months ago 17
Java Question

FileOutputStream(File, append) does not append when writing

this code is part of an object, each object should write its location to the accountstorage.txt, but it writes only the first objects location, even whilst i set append to true

accountstorage = new File(currDir + "/Clients/accountstorage.txt");

try {
if(!accountstorage.exists()) {
accountstorage.getParentFile().mkdirs();
accountstorage.createNewFile();
} else {
return;
}


fos = new FileOutputStream(accountstorage, true);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));


bw.write("@" + accountfile.getParentFile() + "\r\n");
bw.flush();
bw.close();


What could cause this? I can't seem to find the issue myself.

Answer

Because of your conditional block

 if(!accountstorage.exists()) {
    accountstorage.getParentFile().mkdirs();
    accountstorage.createNewFile();
} else {
    return; // DUE to this... Remove else block to fix.
}

When your file does not exists it creates it and write the location but next time when your file exists it returns and do not write anything.

Hope this helps.