# Java : insert line into file



## johnd0e (Mar 14, 2004)

Hi,

I recently started learning Java and now am stuck with a problem I have not been able to figure out for nearly 3 weeks now.

The app:
When finished it shall be used to manage DVD Collections, saving the information in an XML file.

The status quo:
Reading the XML file into a special list model and this into a JTable works, selecting a specific dvd and loading the data into another JFrame also works.

The problem:
Adding a new dvd to the file does not work. 
When using "append mode", the line is appended below the end tag of the XML file, thus rendering it invalid.


The question:
How do I insert a line into a (XML) file? 
 Reading the hole file into a byte array is no real option, since the file might get very big...
Copying the current file into a temporary file, inserting the new dvd a the correct position, deleting the original file and renaming the temp file to the original`s file name is also not a real option...

If anyone of you can give me a hint / tip / link or anything else that helps to figure out this problem, I would really appreciate it...


Thanks for your help in advance


----------



## Viro (Mar 14, 2004)

Looking at what you've written, I'm guessing that you're just reading in the XML file as a normal text file. While that may work if you're doing simple things with it, its a pain if you want to do more.

That's why there are APIs created for such things. Take a look at the DOM and SAX APIs that come with Java. For reading simple files, I use SAX, but if I want to manipulate documents, I'm all for DOM.

What you need is DOM. It basically creates a tree representation of the XML document. So if you want to insert a new line in the XML file, you just insert a new node into the tree. Then when you're done, you just write the whole tree out to a file. All these methods are provided for you, so that'll save a lot of time and headaches.

Chapters 4 - 6 of the J2EE tutorial (http://java.sun.com/j2ee/1.4/docs/tutorial/doc/) should give you all you need to work with XML files in Java. Good luck.


----------



## johnd0e (Mar 14, 2004)

Thanks, I`ll take a look into it


----------

