Sofia
Sofia

Reputation: 456

BufferedWriter.write() method doesn't write integers to file

public void saveToTextFile(String outText) throws IOException
   {

       BufferedWriter out = new BufferedWriter(new FileWriter(outText));
       String[] keys=new String[words.size()];
       int[] values=new int[words.size()];
       int i=0;

       for(String word : words.keySet())
       {
          keys[i]=word;
          values[i]=words.get(word);
          i++;
          if(i==words.size()) //Έχουμε διασχίσει όλο το HashMap
          {
              break;
          }
       }

       bubbleSort(values,keys);

       for(i=0;i<words.size();i++)
       {
           out.write(keys[i]);
           out.write(",");
           out.write(values[i]);
           out.write("\n");
       }

       out.close();
   }

I have the above function and when I open the file it creates it's like: hello, you, are, fine, how, thanks, too, world, and some weird symbols after the first two commas. It's like out.write(values[i]); and out.write("\n"); aren't working! I checked the arrays after the bubbleSort* and they are just fine! The problem appers to be in writing the file...

This is what I get, whick is right:

Word: hello Frequency: 2
Word: you Frequency: 2
Word: are Frequency: 1
Word: fine Frequency: 1
Word: how Frequency: 1
Word: thanks Frequency: 1
Word: too Frequency: 1
Word: world Frequency: 1

Upvotes: 1

Views: 4913

Answers (2)

Anand
Anand

Reputation: 509

You have to write String. Try either of the below

  • out.write("123");
  • out.write(new Integer(123).toString());
  • out.write(String.valueOf(123));

In above example, assuming 123 is written to file.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502106

It's executing exactly as documented

Writes a single character.

Parameters:
c - int specifying a character to be written

I suspect you want:

out.write(String.valueOf(values[i]));

This overrides Writer.write(int), which is slightly more clearly documented:

Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.

Upvotes: 5

Related Questions