Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Wednesday, July 9, 2014

Java program to change the content of files : Java IO

Hello All,

In real time projects we need to change the contents of file, numbers in the file etc.

For example if you have a text file say "source.txt" and you want to replace some text like "abc" with "xyz" as shown below, Java has given a IO library which provides facility to cover this requirement.


Example Image :


Code to replace content of the file source.txt

import java.io.*;
class ReplaceWords
{
public void replaceWord()throws Exception
{
BufferedReader br=new BufferedReader(new FileReader("source.txt"));
StringBuilder sb=new StringBuilder();
while(br.ready())
{
sb=sb.append(br.readLine()+"\n");
}

String data=sb.toString();
data=data.replace("abc","xyz");

FileWriter fw=new FileWriter("destination.txt");
fw.write(data);
fw.flush();
br.close();
fw.close();
}

public static void main(String[] args) throws Exception
{
ReplaceWords rw=new ReplaceWords();
rw.replaceWord();
}
}


Make sure you have a input file "source.txt" in your current working directory, otherwise the above program will throw an exception saying FileNotFound. 

Above code will replace abc in source.txt with xyz and write them in new file destination.txt

If you want to save the contents in same file then just change the name destination.txt in code with source.txt

check below image to see what happens when the file not found.

When source file not found.


To run the above program just paste the above code in java editor and run.

If you run into any issue or have any questions, you can send us an email. Our mail id is diehardtechy@gmail.com

No comments: