SwadhyAI Notes

All Java notes

Java FileOutputStream Reference

›Short versionOpen if you only have a minute.
  • FileOutputStream writes bytes. The one-argument constructor creates or truncates the file immediately.
  • new FileOutputStream(path, true) appends. Parent directories must already exist.
  • write(int) writes the low 8 bits. It does not write the decimal digits of that number.
  • write(byte[]) writes the whole array. A partly filled buffer needs write(buffer, 0, count).
  • flush pushes buffered bytes. close flushes and releases the file. try-with-resources calls close.
  • Text and line endings belong on a Writer, not on this stream.

FileOutputStream writes bytes to a file. It can create, overwrite, or append to files and is commonly wrapped by buffered or text-oriented writers.

Methods

APIParametersReturnsBehaviorWatch for
new FileOutputStream(path)File or path string.Open FileOutputStream.Creates or truncates the target file for writing.Existing content is lost unless append mode is used.
new FileOutputStream(path, true)File/path plus append boolean.Open appending stream.Writes new bytes at the end of the file.Parent directories must already exist.
write(int b)Low 8 bits of an int.void.Writes one byte.Not suitable for writing whole numbers as readable text.
write(byte[] b)Byte array.void.Writes the entire byte array.If buffer is partly filled, use write(b, 0, count).
flush()None.void.Forces pending bytes down the stream chain.close() also flushes, but explicit flush helps before handoff.
close()None.void.Flushes and releases the file resource.Always close, ideally with try-with-resources.

Which call fits

OptionBest forTradeoff
FileOutputStreamBinary output and byte copying.No text encoding or line helpers.
FileWriterSimple character output.Default charset can be surprising.
BufferedOutputStreamMany small byte writes.Requires flush/close discipline.

Examples

Write bytes safely

java
byte[] data = {65, 66, 67};

try (FileOutputStream out = new FileOutputStream("letters.bin")) {
    out.write(data);
}

Append to a binary log

java
try (FileOutputStream out = new FileOutputStream("events.bin", true)) {
    out.write(10); // one newline byte
}

out.write(65) runs on a new FileOutputStream. What byte is in the file, and what is not?

One byte, value 65, which is the character A if you later read the file as text. The digits 6 and 5 are not written. write(int) keeps only the low 8 bits. To write the characters 65, use a Writer and write the string "65".