Java编辑现有文件

Java编辑现有文件

我想通过Java编辑现有文件以使其具有换行符,并在该行的每个第4个字符后跟一个空格,所以下面是期望值。

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})", "$1\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})", "$1\n ");
            bw.write(line);
            bw.newLine();
     }

08-17 19:47