2016-12-23 19 views
-3

我有一個文本:格式化字符串得到公正的話在一列

c:\MyMP3s\4 Non Blondes\Bigger!\Faster, More!_Train.mp3 

我想刪除形式的這段文字,這些文字::,\!._ 和格式化文本,然後像這樣:

c 
MyMP3s 
4 
Non 
Blindes 
Bigger 
Faster 
More 
Train 
mp3 

並將所有這些寫入文件。 這是我做的:

public static void formatText() throws IOException{ 

    Writer writer = null; 
    BufferedReader br = new BufferedReader(new FileReader(new File("File.txt"))); 

    String line = ""; 
    while(br.readLine()!=null){ 
     System.out.println("Into the loop"); 

     line = br.readLine(); 
     line = line.replaceAll(":", " "); 
     line = line.replaceAll(".", " "); 
     line = line.replaceAll("_", " "); 

     line = System.lineSeparator(); 
     System.out.println(line); 
     writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Write.txt"))); 
     writer.write(line); 
    } 

而且它不工作!

例外:

Into the loop 
Exception in thread "main" java.lang.NullPointerException 
    at Application.formatText(Application.java:25) 
    at Application.main(Application.java:41) 
+1

您是不是要找'線+ = System.lineSeparator();'? –

+0

你可以請發佈該程序的輸出是什麼? – SteelToe

+0

@ PM77-1我會寫輸出 –

回答

1

在你的代碼的最後,你必須:

line = System.lineSeperator()

這將重置您的替代品。另外需要注意的是String#replaceAll爲第一個參數提供了正則表達式。所以,你必須轉義任何序列,如.

String line = "c:\\MyMP3s\\4 Non Blondes\\Bigger!\\Faster, More!_Train.mp3"; 
System.out.println("Into the loop"); 

line = line.replaceAll(":\\\\", " "); 
line = line.replaceAll("\\.", " "); 
line = line.replaceAll("_", " "); 
line = line.replaceAll("\\\\", " "); 

line = line.replaceAll(" ", System.lineSeparator()); 

System.out.println(line); 

輸出是:

Into the loop 
c 
MyMP3s 
4 
Non 
Blondes 
Bigger! 
Faster, 
More! 
Train 
mp3