2013-02-13 141 views
-3

我已經計算出了這些字,現在顯示在控制檯中。但我想將控制檯輸出寫入文本文件。這個怎麼做?如何在java中的文本文件中打印此輸出?

String[] wrds = counter.getWords(WordCounter.SortOrder.BY_FREQUENCY); 
int[] frequency = counter.getFrequencies(WordCounter.SortOrder.BY_FREQUENCY);   

int n = counter.getEntryCount(); 
for (int i=0; i<n; i++) 
{ 
    This should be written in text file///// System.out.println(frequency[i] + " " + wrds[i]+" "+ counter.getWordCount()); 
+0

您是否嘗試過在此搜索教程?如果你只是谷歌「Java寫入文件」或類似的東西,有很多很棒的例子。 – Quetzalcoatl 2013-02-13 15:25:11

+0

我使用Google搜索確切的問題標題。這是我的第二擊:http://stackoverflow.com/questions/1994255/how-to-write-console-output-to-a-txt-file – djechlin 2013-02-13 15:27:00

+0

所有的朋友。我試過1994255的例子,但如果它不工作,它不工作 – Ameer 2013-02-13 15:28:37

回答

2
String[] wrds = counter.getWords(WordCounter.SortOrder.BY_FREQUENCY); 
int[] frequency = counter.getFrequencies(WordCounter.SortOrder.BY_FREQUENCY);   
String texttoWrite = ""; 
int n = counter.getEntryCount(); 
for (int i=0; i<n; i++) 
{ 
    texttoWrite += frequency[i] + " " + wrds[i]+" "+ counter.getWordCount(); 
} 
try{ 
FileWriter fstream = new FileWriter("out.txt"); 
BufferedWriter out = new BufferedWriter(fstream); 
out.write(texttoWrite); 
out.close(); 
}catch (Exception e){ 
    System.err.println("Error: " + e.getMessage()); 
} 
} 
+1

更新了代碼。嘗試一下。 – NEO 2013-02-13 15:38:49

+0

謝謝,但我想寫成一行行。 texttoWrite + = frequency [i] +「」+ wrds [i] +「」+ counter.getWordCount()+「\ n」; } 是正確的嗎? – Ameer 2013-02-13 15:47:43

+1

是的。您必須追加一個新的換行符才能逐行打印。 – NEO 2013-02-13 15:50:08

0

這樣的事情呢?

FileWriter fstream = new FileWriter(fileName); 
BufferedWriter fbw = new BufferedWriter(fstream); 
for (int i=0; i<n; i++) { 
    fbw.write(frequency[i] + " " + wrds[i]+" "+ counter.getWordCount()+ "\n"); 
} 
0

退房FileWriter

FileWriter fw = new FileWriter("path location"); 
fw.write(frequency[i]....); 
fw.close(); 
0

打開該文件對象的文件。並寫入文件而不是控制檯(或兩者兼而有之)。關閉文件。什麼是真正的問題?