Java File Writing Quesiton

Status
Not open for further replies.
I'm trying to write an array of strings back to a file. Can I just write the whole array back at once? I would think I could but I'm having issues. Here's the code:

public void update_File(Card_Reader card_reader1)
{
records = card_reader1.get_Record_Array();
records[index] = updatedRecord;

try {
FileWriter outStream = new FileWriter("Records2.dat");
outStream.write(records);
outStream.close();
} catch(IOException e) {
e.printStackTrace();
}

}


What's the problem with just trying to write records back? Do I need to use a for loop and send each part of the array to a temp string before I write it?

Thanks
 

gumbo

Ars Tribunus Angusticlavius
6,107
You can serialize it using ObjectOutputStream and ObjectInputStream - these will record all the info for the array, then reconstruct it when you load it.

To do each of the elements, you can do this:
code:<HR>
Code:
for (int i=0; i < records.length; i++) {
    outStream.write(records[i]);
}

This assumes write can accept whatever you have in the array. Serializing takes more space, and is 'cheating', but IMO it is easier. The only problem is many tings can't be serialized. They must implement the Serializable interface. Everything can be written using write and other such methods, some how.

gubmo
 
Ok I got that to fix my problem. Now I have a small issue. When I write back to the text file, it doesn't put each entry on a separate line.I do this:

for (int i = 0; i<records.length ; i++)
{
outStream.write(records + "\n");
}


It gives me all the strings on one line separated by a sqaure []. I guess that's the symbol for carrige return, because the file reads it in ok in that format. Is there a way to get it to put each record on each line properly? I'm viewing these files using Notepad.

Thanks
 
Status
Not open for further replies.