I need to check for a particular word from an existing file and need to replace that word with new word.How should i do this? Now i can able to read that particular word from the existing file.But i dont know how to replace that particular word with new word.
Campbell Ritchie wrote:Can you replace things in a random access file like that? I thought they would have to be exactly the same length, but I might be mistaken.
You're not. Although you can shift bytes and if necessary truncate the RandomAccessFile, originally it only allows replacing bytes with the same number of bytes. It shouldn't be used for replacing characters at all because of encodings. That's why I posted the "editing an existing file" FAQ, because that's a better solution.
I'd advise to save yourself a lot of headaches and use a proper tool for the job: If you want to alter an XML file, that's what libraries like DOM, JDOM and XOM are for. Using string operations (or regular expressions or something else of that nature) on XML *will break* eventually when the file format changes in a way that the code doesn't foresee.
DOM is part of the JAXP API (which is the standard Java API for XML handling), and JAXP is part of the JRE, so you don't need to download or install anything. The XmlFaq contains links to numerous articles that should get you started.
The reason I mentioned other libraries like JDOM and XOM is that the DOM API, while perfectly functional, isn't specifically designed for Java -which JDOM and XOM are- so it is a bit awkward to work with.
It's just like a fortune cookie, but instead of a cookie, it's pie. And we'll call it ... tiny ad:
a bit of art, as a gift, that will fit in a stocking