Java – Edit File Example, Modify File java

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

Tags:

Bookmark  

 

4 Responses to “Java – Edit File Example, Modify File java”

  1. vishakha says:

    Thanks for your support, its really help me a lot.

  2. fer says:

    code is working but I have one problem,
    I have this record in my info.text
    name: fern
    age:20

    after I replace the word of “fern”
    it will make a one line ” name: NEWNAMEage:20 ”
    which is I want to keep the original position and just replace the word I want to replace.
    please mail me how to do it. Tnx!

  3. baxou says:

    It is quite an interesting code which helped me a lot, but there are some clumsy things about it.

    First of all using a while(true) loop is not a good idea. It would be better if you did it like this so it is easier to read :
    String textinLine=br.readLine();
    while(textinLine != null)
    {
    sb.append(textinLine + “\n”); // if you don’t put the \n you will have all the code on one line as fer said
    textinLine=br.readLine(); // do not put the \n here unless you want to experience an exquisite exception.
    }

    Then you should create a method to do replacements easier without needing to copy/paste the code each time, and besides, it is actually doing only one replacement and this is not kinda effective for people wishing to make multiple replacements. What do you think about this :

    // if you want to put this in the same class as your main do not forget to use the static keyword to declare the method
    public void replace(String textToEdit, String textToReplaceWith) {
    int cnt = sb.indexOf(textToEdit);
    while(cnt != -1) { // so it will replace every occurence until there is no more left
    sb.replace(cnt2,cnt+textToEdit.length(), textToReplaceWith);
    cnt = sb.indexOf(textToEdit);
    }
    }

    To continue these three lines of code are an error of logic since fs is used to create in which is used to create br :
    fs.close();
    in.close();
    br.close();
    They should be reversed :
    br.close();
    in.close();
    fs.close();

    Have a nice day.

  4. baxou says:

    Sorry for the indentation, I didn’t know how to put it on (i thought it would take the spaces I made)

Leave a Reply

Security Code:

 

  Random Post