Write to file using BufferedOutputStream

This code snippet shows how to write to a file using a BufferedOuputStream.
Now it should be said that if you want to write text to a file you should probably find it easier to go with a Writer class like the BufferedWriter instead.
The write method of the BufferedOuputStream takes either a byte array or an int as argument so that is why we have to call getBytes() on any String that we provide to the write method.
The getBytes method of the String class returns its content in the form of a byte array.
The other overloaded variant of the write method that takes an int as an argument prints the character that has the decimal value (or ascii value if you want) that matches the parameter.
So in the example below we call write with 65 as the argument, which is the same as character ‘A’.

Note that the construction of a BufferedOutputStream as below will overwrite any file with the same name that already exists.

If you run the code the contents of the file should look like this:

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?