top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to replace a particular word by another word in a file in java?

0 votes
52 views
How to replace a particular word by another word in a file in java?
posted Jul 7, 2017 by Ajay Kumar

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

+1 vote

There is a inbuilt function called replaceAll to do this in a sting. So steps would be to read whole file in a string apply the function replaceAll and write this new string in the file.

import java.io.*;

public class BTest
    {
     public static void main(String args[])
         {
         try
             {
             File file = new File("file.txt");
             BufferedReader reader = new BufferedReader(new FileReader(file));
             String line = "", oldtext = "";
             while((line = reader.readLine()) != null)
                 {
                 oldtext += line + "
";
             }
             reader.close();

             String newtext = oldtext.replaceAll("Ajay", "Salil");

             FileWriter writer = new FileWriter("file.txt");
             writer.write(newtext);writer.close();
         }
         catch (IOException ioe)
          {
             ioe.printStackTrace();
         }
     }
}
answer Jul 8, 2017 by Salil Agrawal
Similar Questions
+3 votes

If you use fread to read a file of unknown size with a set buffer size of say 500 bytes, when you get to the end of the file you are likely to read a stub of 500 bytes of info and the eof marker.

And fread will not read that block and set and oef that can be read with feof. That is how I understand, so we can either use fseek to discover the file size and fread accordingly or use fstat?

Is this the proper approach?

0 votes

I need to write into a file for a project which will be evaluated on the basis of time. What is the fastest way to write 200 Mb of data, accumulated as a list into a file.

Presently I am using this:

with open('index.txt','w') as f:
 f.write("".join(data))
 f.close()

where data is a list of strings which I want to dump into the index.txt file

+3 votes

When opening a file, you'd say whether you want to read or write to a file. This is fine, but say for example later on in the program I change my mind and I want to write to a file instead of reading it. Yes, I could just say 'r+w' when opening the file, but what if I don't know if I'm going to do both? What if I have the user decide, and then later on I let the user change this.

Is it possible to do so without opening the file again and using the same file object?

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...