here is my code
try {
fstream = new FileWriter("/Applications/AirDrop/contacts.txt");
BufferedWriter out = n开发者_开发问答ew BufferedWriter(fstream);
out.write(stringToInsert);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
now everytime I try to call this method (this is code is in a method called writeToFile with a string parameter) the string which
You need to use the two-argument constructor of FileWriter
:
fstream = new FileWriter("/Applications/AirDrop/contacts.txt", true);
Better yet: don't use FileWriter
at all, because it always uses the platform default encoding, which is not usually a good idea! Instead you should explicitly specify which encoding to use (UTF-8 is usually a good default, if you don't know what else to chose):
fstream = new OutputStreamWriter(new FileOutputStream("/Applications/AirDrop/contacts.txt", true), "UTF-8");
Another hint: it is pretty likely that constantly opening and closing the file is not the best idea: You should usually open the file once for writing, write everything you need to write to it and then close it.
精彩评论