Search code examples
javainttext-filesjtextfieldbufferedwriter

Buffered writer writes memory trash on text file


My buffered writer is writting some randomly trash in my txt file. I use int nodes = Integer.valueOf(NODES_TEXT_FIELD.getText()); to store the value of one TextField that should only accept ints.

this is my writer:

 private static void writeOnFile(BufferedWriter writer, int nodes){

           try {
               System.out.println(nodes);
               System.out.println("Last check before write");
                writer.write(nodes);
                System.out.println(nodes);
        } catch (IOException e) {

            JOptionPane.showMessageDialog(null, "Failed to write data on file");
                e.printStackTrace();            
        }      
       }

My output:

2
Last check before write
2

and in the text file I found: '?' (which changes to another memory trash depending on what number you input

Anybody has any Idea of what might be wrong? I stuck here for 5 hours until now..


Solution

  • Because write() writes a character .

    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.

    Parameters:

    c - int specifying a character to be written

    You can use Writer#write(String):

    writer.write(String.valueOf(nodes));