Posts Tagged java.io

Java – Edit File Example, Modify File java

Sunday, December 20th, 2009

File can be appended by File class and other input output stream. To write content in a file in java we need to use java.io package. File class is used to create a file at specific path. We can use either StringBuffer for text and content to store in file. In java we can write file with FileWriter class with BufferedWriter class. write() method is used to create file and write the content in file.

To edit file in java we need to search text which replace with new text. indexOf() method will search text in java and append() method will modify old content in string.

This example will explain how to edit file in java and modify text in file by java.

text file in c drive

Content in this text, abc change xyz with new content by java io package

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaIOEditFileExample {

    public static void main(String[] args) {

        File f=new File("c:\\appendOldFile.txt");

        FileInputStream fs = null;
        InputStreamReader in = null;
        BufferedReader br = null;

        StringBuffer sb = new StringBuffer();

        String textinLine;

        try {
             fs = new FileInputStream(f);
             in = new InputStreamReader(fs);
             br = new BufferedReader(in);

            while(true)
            {
                textinLine=br.readLine();
                if(textinLine==null)
                    break;
                sb.append(textinLine);
            }
              String textToEdit1 = "abc";
              int cnt1 = sb.indexOf(textToEdit1);
              sb.replace(cnt1,cnt1+textToEdit1.length(),"New Append text");

              String textToEdit2 = "xyz";
              int cnt2 = sb.indexOf(textToEdit2);
              sb.replace(cnt2,cnt2+textToEdit2.length(),"Second new edit text");

              fs.close();
              in.close();
              br.close();

            } catch (FileNotFoundException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }

            try{
                FileWriter fstream = new FileWriter(f);
                BufferedWriter outobj = new BufferedWriter(fstream);
                outobj.write(sb.toString());
                outobj.close();

            }catch (Exception e){
              System.err.println("Error: " + e.getMessage());
            }
    }
}

Output

Content in this text, New Append text change Second new edit text with new content by java io package