2016-04-28 74 views
0

我想通過Java編輯現有的文件,在行的每個第4個字符後面都有一個換行符,後跟一個空格。所以下面是期望值。Java編輯現有文件

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); 

    } 
+0

您對此代碼有什麼問題? – Sanjeev

+0

@Sanjeev根據問題''但這寫在一個單一的所有行'# –

+0

如果您使用'「$ 1」+ System.getProperty(「line.separator」);'而不是'「$ 1 \ n」? – npinti

回答

1

您的代碼在每行之後沒有寫行分隔符。您需要特別添加它

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

或'bw.newLine();' –

+0

同意。謝謝,這將是系統獨立的。 – Sanjeev