My brother asked me an interesting task. I took it on to solve it and it was very simple in the end using the RandomAccessFile class
The task is to replace a single character occurrences in all the places of the file. You can say that it's very easy as you can have a holding area and rename the file in the end. But the file shouldn't be replaced on the disk or files content shouldn't be replaced using the buffer data
I've used RandomAccessFile class to accomplish this task
ReplaceCharacterInFile.javapackage my.own; import java.io.RandomAccessFile; /** * This class replaces all the occurrences of a single character within * the file mentioned without actually replacing the file on the disk. * @author SANTHOSH REDDY MANDADI * @version 1.0 * @since 17-December-2018 */ public class ReplaceCharacterInFile { public static void main(String[] args) throws Exception { //Variable to hold the file name where the replacement to happen String fileName = "Santhosh.txt"; //Variable to indicate character to find char findChar = 's'; //Variable to indicate the character to replace char replaceChar = 'S'; //Opening the file - please handle exception, I've just throws the exception since it's a demo RandomAccessFile file = new RandomAccessFile(fileName,"rw"); int count = 0; int ch; try { do { ch = file.read(); if(ch==findChar) { file.seek(file.getFilePointer()-1); file.write(replaceChar); count++; } }while(ch!=-1); System.out.println(count+" character occurances of "+findChar+" are now been replaced with "+replaceChar+" in "+fileName); } finally { if(file!=null) { file.close(); } } } }
I've the text file placed in the same folder which contains some text, here the text and output after running the program
Santhosh.txtSanthosh Reddy Mandadi santhosh reddy santhosh reddy mandadiOutput
santhosh>java ReplaceCharacterInFile
5 character occurances of s are now been replaced with S in Santhosh.txt
If you open the file now, you should see the small s being replaced with capital S.
Santhosh.txt
SanthoSh Reddy Mandadi SanthoSh reddy SanthoSh reddy mandadi