-3

I have calculated the words and now displaying it in console. But I want to write the console output to a text file. how to do this?

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());
darcyy
  • 5,236
  • 5
  • 28
  • 41
Ameer
  • 600
  • 1
  • 12
  • 27
  • Have you tried searching for tutorials on this at all? There is a plethora of great examples if you just google "java writing out to a file" or similar. – Quetzalcoatl Feb 13 '13 at 15:25
  • I googled your exact question title. This is my 2nd hit: http://stackoverflow.com/questions/1994255/how-to-write-console-output-to-a-txt-file – djechlin Feb 13 '13 at 15:27
  • All friends. I tried the example 1994255 but its not working – Ameer Feb 13 '13 at 15:28
  • if it isn't working, then post the error (stacktrace) you got – roel Feb 13 '13 at 15:33

4 Answers4

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());
 }
}
NEO
  • 1,961
  • 8
  • 34
  • 53
0

How about something like this?

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");
}
nwinkler
  • 52,665
  • 21
  • 154
  • 168
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
0

Check out FileWriter

FileWriter fw = new FileWriter("path location");
fw.write(frequency[i]....);
fw.close();
Joey
  • 544
  • 1
  • 6
  • 21
0

Open a file with the file object. And write to the file in stead of the console (or do both). Close the file. What is the real problem?

roel
  • 2,005
  • 3
  • 26
  • 41