Search code examples
javafileoutputstream

How to write an integer in a file using FileOutputStream?


When i want to write a text in a file i converted it to a byte and then save it in a byte array and then send it with the FileOutputStream to the file. What should i do if i want to write an integer ??

    String filename = "testFile.txt";
    OutputStream os = new FileOutputStream(filename);
    String someText = "hello";
    byte[] textAsByte = someText.getBytes();
    os.write(textAsByte);

    int number = 20;
    byte numberAsByte = number.byteValue();
    os.write(numberAsByte);

I am getting (Hello) expected result: Hello20


Solution

  • You're not really wanting to write the integer. What you are looking to do is write the string representation of the integer. So you need to convert it to a String which you can easily do with String.valueOf() so that 20 becomes "20"

       os.write(String.valueOf(number).getBytes())
    

    If the file is a text file you could consider using a Writer instead of an OutputStream which means you don't have to worry about bytes.

       String filename = "testFile.txt";
       try (BufferedWriter out = new BufferedWriter(new FileWriter(filename))) {
            out.write("hello");
            out.write(String.valueOf(20));
       }
    
    

    Also use the try-with-resource to wrap your OutputStream or Writer so that you don't have to worry about closing the stream should anything unexpected happen.