Skip to main content

writing to file

2 replies [Last post]
purple_chicken
Offline
Joined: 2009-11-23

I'm trying to write contact details to a file. The code I've written so far writes all the details in a single line and i want each item to be on a new line. How do I do this?

try
{
BufferedWriter addressbook = new BufferedWriter(new FileWriter("AddressBook.buab"));

addressbook.write(surname.getText());
addressbook.write(firstname.getText());
addressbook.write(homephonenumber.getText());
addressbook.write(mobilenumber.getText());
addressbook.write(address.getText());

addressbook.close();
}

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

Also, I think that every time I run the program and write to the file, it is going to write over what was stored there previously. How would I go about adding that data onto the end of the current data, rather than replacing it?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
peter__lawrey
Offline
Joined: 2005-11-01

try the following to append lines to a file.

PrintWriter pw = new PrintWriter(new FileWriter("myfile", true));
pw.println(surname.getText());
// more fields.
pw.close();

http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html
http://java.sun.com/j2se/1.4.2/docs/api/java/io/PrintWriter.html

purple_chicken
Offline
Joined: 2009-11-23

Thank you, everything is working properly now. :-)