Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and edit the file from Java

I'm trying to introduce a line break at every 100th character of the line from the existing file.But it doesn't write anything to it. below is the code written in java to read the existing file and write to it with a temporary file.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ReplaceFileContents {
   public static void main(String[] args) {
     new ReplaceFileContents().replace();
   }

   public void replace() {
      String oldFileName = "Changed1.ldif";
      String tmpFileName = "Changed2.ldif";

      BufferedReader br = null;
      BufferedWriter bw = null;
      try {
         br = new BufferedReader(new FileReader(oldFileName));
         bw = new BufferedWriter(new FileWriter(tmpFileName));
         String line;
         while ((line = br.readLine()) != null) {       
                line.replaceAll("(.{100})", "$1\n");       
         }
      } catch (Exception e) {
         return;
      } finally {
         try {
            if(br != null)
               br.close();
         } catch (IOException e) {
            //
         }
         try {
            if(bw != null)
               bw.close();
         } catch (IOException e) {
            //
         }
      }
      // Once everything is complete, delete old file..
      File oldFile = new File(oldFileName);
      oldFile.delete();

      // And rename tmp file's name to old file name
      File newFile = new File(tmpFileName);
      newFile.renameTo(oldFile);

   }
}
like image 509
eshaa Avatar asked Feb 15 '26 23:02

eshaa


1 Answers

while ((line = br.readLine()) != null) {       
    line.replaceAll("(.{100})", "$1\n");       
}

First off, line.replaceAll does not replace your line variable with the result. Because Strings are immutable, this method returns the new string, so your line should be line = line.replaceAll(....

Second, you're never writing the new String back into the file. Using replaceAll doesn't change the file itself in any way. Instead, try using your bw object to write the new String to the same line.

like image 189
Zircon Avatar answered Feb 17 '26 21:02

Zircon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!