Java 编辑现有文件

Java to edit the existing file

我想通过 Java 编辑现有文件以添加一个换行符,然后在 line.So 的每个第 4 个字符后跟一个 space 说是预期。

File Content
------------
abcdef
gh
ijklmn

Expected output
--------------
abcd
 ef
gh
ijkl
 mn

下面是试过的代码,但它写在一行中。

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=line.replaceAll("(.{4})", "\n ");       
                bw.write(line);
         }
      } 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);

   }

您的代码没有在每行之后写一个行分隔符。需要专门添加

     while ((line = br.readLine()) != null) {       
            line=line.replaceAll("(.{4})", "\n ");       
            bw.write(line);
            bw.newLine();
     }