Home » Java » java – Writing an Integer in file with BufferedWriter-Exceptionshub

java – Writing an Integer in file with BufferedWriter-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

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?

How to&Answers:

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.