Share on Google+Share on Google+

How to update a file

Advertisement
In this section, you will learn how to update the text file.

How to update a file

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:

import java.io.*;

public class UpdateFile {
  public static void main(String[] argsthrows Exception {
    File f = new File("c:/new.txt");
    StringBuffer buffer = new StringBuffer();
    String str;
    BufferedReader br = new BufferedReader(new FileReader(f));
    while (true) {
      str = br.readLine();
      if (str == null)
        break;
      buffer.append(str);
    }
    String st1 = "All";
    int c1 = buffer.indexOf(st1);
    buffer.replace(c1, c1 + st1.length()"Some");

    String st2 = "not gold";
    int c2 = buffer.indexOf(st2);
    buffer.replace(c2, c2 + st2.length()"Diamond");
    br.close();
    BufferedWriter bw = new BufferedWriter(new FileWriter(f));
    bw.write(buffer.toString());
    bw.close();
  }
}

Advertisements

Advertisement

Posted on: April 3, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.