0

I have a method to write a file but somehow it is having problems writing an int:

public static void writeFile(int[] result) {
    try {
        FileWriter writer = new FileWriter("MyFileExample.txt", true);
        BufferedWriter bufferedWriter = new BufferedWriter(writer);

        int counter = 0;
        for (int j = 0; j < result.length; j++) {
            if (result[j] != -1) {
                counter++;
            }
        }
        System.out.println(counter);


        bufferedWriter.write(counter);

        bufferedWriter.newLine();

        for(int i = 0; i<result.length; i++) {
            if (result[i] != -1) {
                bufferedWriter.write(i + " ");
            }
        }






        bufferedWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The line bufferedWriter.write(counter); is not writing anything. Just a blank. The rest is getting written perfectly fine. I tried writing "test" instead of counter and that is perfectly fine as well.

Any idea on how to fix this issue?

Chris
  • 1,828
  • 6
  • 40
  • 108
  • 2
    Note that [`BufferedWriter#write(int)`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/io/BufferedWriter.html#write(int)) (inherited from [`Writer#write(int)`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/io/Writer.html#write(int))) is for writing a single _character_, not an _integer_. – Slaw Feb 17 '20 at 15:27
  • so how do I solve that? – Chris Feb 17 '20 at 15:31
  • 1
    try `write(Integer.toString(counter))`. – holi-java Feb 17 '20 at 15:34
  • works perfeclty thanks! – Chris Feb 17 '20 at 15:35

1 Answers1

2

What happened, when you wrote the int without converting it into a String is, it simply wrote the int as the type it is (an int). So invoking the method e.g. as follows:

writeFile(new int[] {1, 2, 3})

writes the following bytes to the file:

03 00 01 02

which, if you refer to an ASCII table, are all non-printable characters.

Based on the filetype you want to write, I assume, you want the Integers to be written as Strings. So you just did the right thing to convert it before writing it.

Jan Held
  • 634
  • 4
  • 14