2013-07-28 127 views
1

我想一個符號化的字符串保存到文本文件... 例,在Read.txt是:將一個Tokenized字符串寫入一個文本文件?

She sells, sea shells, by the sea shore.

我得到了我的程序來標記它,但我似乎無法保存令牌化串入Write.txt

Write.txt我只是得到:

She sells, sea shells, by the sea shore.

基本上我想要什麼,我輸出保存到Write.txt

任何幫助,將不勝感激:d

這裏是我的輸出:

She sells, sea shells, by the sea shore. 

[Split by spaces.] 

She 
sells, 
sea shells, 
by 
the 
sea 
shore. 

----------------------------- 

[Split by commas.] 

She sells 
sea shells 
by the sea shore. 

而且我目前的代碼:

import java.io.*; 
import java.util.StringTokenizer; 


public class readWriteTokenized{ 
public static void main(String[] args){ 

    String readString; 

    try{ 
     BufferedReader br = new BufferedReader(new FileReader("Read.txt")); 

     readString = br.readLine(); 
     System.out.println("\n" + readString); 

     br.close(); 


     StringTokenizer stnz = new StringTokenizer(readString); 

     System.out.println("\n[Split by spaces.]\n"); 
     while(stnz .hasMoreTokens()){ 
      System.out.println(stnz .nextToken()); 
     } 


     StringTokenizer stnz2 = new StringTokenizer(readString, "."); 

     System.out.println("\n-----------------------------"); 
     System.out.println("\n\n[Split by comma.]\n"); 
     while(stnz2.hasMoreTokens()){ 
      System.out.print(stnz2.nextToken()); 
     } 


     File NewTextFile = new File("C:/TestJava/Write.txt"); 

     FileWriter fw = new FileWriter(NewTextFile); 
     fw.write(readString); 
     fw.close();  
    } 
    catch (IOException e){ 
     System.out.println("Catch error!"); 
    }  
    } 
} 

回答

2

你需要每個令牌write(),附加System.getProperty("line.separator")。示例代碼將是:

while(stnz2.hasMoreTokens()){ 
    fw.write(stnz2.nextToken()+System.getProperty("line.separator")); 
} 

或者,您可以decorateFileWriterPrintWriter並使用其println()方法進行格式化。

+0

酷!有用!時間稍微亂了一下,謝謝你的回覆:D –

相關問題