All the file operations have to be performed using java.io.* package. You have already learnt various file operations. In this section, you will learn how to update the text file.
Description of code:
We have used FileReader and BufferedReader class to read the content from the file and stored it into the StringBuffer. Now to edit the file, we have used the indexOf() method to search the specified text from the buffer and then using the replace() method , we have modified the specified content with the new one. This buffered string is then write into the file using FileWriter and BufferedWriter class.
StringBuffer- This class is used to store strings that can be changed.
readLine() method- This method of BufferedReader class read the line from the file.
write() method- This method of BufferedWriter class writes the content into the file.
append() method- This method of StringBuffer class appends the string to the StringBuffer.
indexOf(String s) method- This method of StringBuffer returns the index of the specified string.
replace() method- This method of StringBuffer class replaces the characters in a substring with characters in the specified String.
Content of text file: new.txt:
|Hello World, All glitters are not gold.|
Here is the code:
Posted on: April 3, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles