2016-10-07 122 views
0

我想格式化文本文件。我想要刪除所有新行字符,除了用於啓動新的alinea的字符外。我的意思是如果文本文件中的行是空格,我想保留它,但所有其他換行符都需要刪除。格式化文本文件java

這裏是我到目前爲止有:

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.util.Scanner; 


public class Formatting { 
    public static void main(String[] args) throws FileNotFoundException { 
     Scanner in = new Scanner(System.in); 
     System.out.println("give file name: "); 
     String filename = in.next(); 
     File inputfile = new File(filename); 
     Scanner reader = new Scanner(inputfile); 
     String newline = System.getProperty("line.separator"); 

     PrintWriter out = new PrintWriter("NEW " + filename); 

     while(reader.hasNextLine()) { 
      String line = reader.nextLine(); 


      if (line.length() > 2 && line.contains(newline)) { 
       String replaced = line.substring(0,line.length()) + ' '; 
       out.print(replaced); 
      } 
      else { 
       out.print(line + ' '); 
      } 

     } 
     in.close(); 
     out.close(); 
    } 
} 

但是現在我的第一個if語句永遠不會被執行。每一個換行符都會被刪除。

有人可以幫我嗎?非常感謝。

回答

1

這可能會幫助你,閱讀評論,以瞭解每條線的用途。

// 3.壓縮多個換行到單個換行

  line = line.replaceAll("[\\n]+", "\n"); 


      // 1. compress all non-newline whitespaces to single space 

      line = line.replaceAll("[\\s&&[^\\n]]+", " "); 


      // 2. remove spaces from begining or end of lines 
      line = line.replaceAll("(?m)^\\s|\\s$", "");