Java编辑现有文件

时间:2016-04-28 05:43:40

标签: java filereader filewriter bufferedwriter

我想通过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);

   }

1 个答案:

答案 0 :(得分:1)

您的代码不是在每行之后写一个行分隔符。你需要专门添加它

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