# FileOutputStream

### Java FileOutputStream Example

Here is a simple Java `FileOutputStream` example:

```
OutputStream output = new FileOutputStream("c:\\data\\output-text.txt");

while(moreData) {
  int data = getMoreData();
  output.write(data);
}
output.close();
```

Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to [Java IO Exception Handling](https://jenkov.com/tutorials/java-io/io-exception-handling.html). There is also an example of better exception handling at the bottom of this tutorial, in the section about closing a Java `FileOutputStream`.

### FileOutputStream Constructors

The Java `FileOutputStream` class contains a set of different useful constructors. I will cover the most commonly used constructors here.

The first constructor takes a `String` which contains the path of the file to write to. Here is an example:

```
String path = "C:\\users\\jakobjenkov\\data\\datafile.txt";

FileOutputStream output = new FileOutputStream(path);
```

Notice the `path` `String`. It needs double backslashes (`\\`) to create a single backslash in the `String`, because backslash is an escape character in Java Strings. To get a single backslash you need to use the escape sequence `\\`.

On unix the file path could have looked like this:

```
String path = "/home/jakobjenkov/data/datafile.txt";
```

The second `FileOutputStream` constructor takes a [Java File](https://jenkov.com/java-io/file.html) object which points to the file in the file system. Here is an example:

```
String path = "C:\\users\\jakobjenkov\\data\\datafile.txt";
File   file = new File(path);

FileOutputStream output = new FileOutputStream(file);
```

#### Overwriting vs. Appending the File

When you create a Java `FileOutputStream` pointing to a file that already exists, you can decide if you want to overwrite the existing file, or if you want to append to the existing file. You decide that based on which of the `FileOutputStream` constructors you choose to use.

This constructor which takes just one parameter, the file name, will overwrite any existing file:

```
OutputStream output = new FileOutputStream("c:\\data\\output-text.txt");
```

There is a constructor that takes 2 parameters too: The file name and a `boolean`. The boolean indicates whether to append to the file or not. Thus, a value of `true` means that you want to append to the file, whereas a value of `false` means you want to overwrite the file. Here are two Java `FileOutputStream` constructor examples:

```
OutputStream output = new FileOutputStream("c:\\data\\output-text.txt", true); //append

OutputStream output = new FileOutputStream("c:\\data\\output-text.txt", false); //overwrite
```

When you leave out the second `boolean` parameter and thus just use the constructor that takes a file path, the default mode is to overwrite any existing file on the given path.

### write()

To write data to a Java `FileOutputStream` you can use its `write()` method. The `write()` method takes an `int` which contains the byte value of the byte to write. **Thus, only the lower 8 bit of the passed `int` actually gets written to the `FileOutputStream` destination**. Here is an example of writing data to a Java `FileOutputStream` using its `write()` method:

```
OutputStream outputStream = new FileOutputStream("c:\\data\\output-text.txt");

outputStream.write(123);
```

This example writes the byte value `123` to the given Java `FileOutputStream`.

<details>

<summary>How int (4 bytes) is truncated to bute (1 byte) while writing to stream</summary>

[Link](https://stackoverflow.com/q/19402568)

write() method in FileOutputStream takes an int but truncates the first 3 bytes and writes the byte to stream. If a file contains characters whose ASCII value is more than 127 and bytes are read from it and then written to output stream(another text file) how will it display it because in Java bytes can have a max value of +127.

If a text file(input.text) has character '›' whose ASCII value is 155. An input stream,input, reads from it : `int in= new FileInputStream("input.txt").read();//in = 155`

Now it writes to another text file(output.txt)

`new FileOutputStream("output.txt").write(in);`

**Answer:**

I think your confusion is caused by the fact that specs for character sets typically take the view that bytes are unsigned, while Java treats bytes as signed.

In fact `155` as an unsigned byte is `-101` as a signed byte. (`256 - 101 == 155`). The bit patterns are identical. It is just a matter of whether you *think* of them as signed or unsigned.

How the truncation is coded is implementation specific. But there is no loss of information ... assuming that you had an 8-bit code in the first place.

</details>

### Writing Byte Arrays

Since the Java `FileOutputStream` is a subclass of [OutputStream](https://jenkov.com/tutorials/java-io/outputstream.html), you can write arrays of bytes to the `FileOutputStream` too, instead of just a single byte at a time. Here is an example of writing an array of bytes to a Java `FileOutputStream` :

```
OutputStream outputStream = new FileOutputStream("c:\\data\\output-text.txt");

byte bytes =  new byte[]{1,2,3,4,5};

outputStream.write(bytes);
```

### Write Performance

It is faster to write an array of bytes to a Java FileOutputStream than writing one byte at a time. The speedup can be quite significant - up to 10 x higher or more. Therefore it is recommended to use the `write(byte[])` methods whenever possible.

The exact speedup you get depends on the underlying OS and hardware of the computer you run the Java code on. The speedup depends on issues like memory speed, hard disk speed and buffer sizes.

### Transparent Buffering via BufferedOutputStream

You can get transparent buffering of bytes written to a Java `FileOutputStream` by wrapping it in a [Java BufferedOutputStream](https://jenkov.com/tutorials/java-io/bufferedoutputstream.html) . All bytes written to the `FileOutputStream` will first get buffered inside an internal byte array in the `BufferedOutputStream`. When the buffer is full, the buffer is flushed to disk all at once. Here is an example of wrapping a Java `FileOutputStream` in a `BufferedOutputStream`:

```
int bufferSize = 8 * 1024;
FileOutputStream output = new BufferedOutputStream(
                      new FileOutputStream("c:\\data\\output-file.txt"),
                          bufferSize
);
```

You can more about the `BufferedOutputStream` in my [BufferedOutputStream tutorial](https://jenkov.com/tutorials/java-io/bufferedoutputstream.html).

### flush()

When you write data to a Java `FileOutputStream` the data may get cached internally in the memory of the computer and written to disk at a later time. For instance, every time there is X amount of data to write, or when the `FileOutputStream` is closed.

If you want to make sure that all written data is written to disk without having to close the `FileOutputStream` you can call its `flush()` method. Calling `flush()` will make sure that all data which has been written to the `FileOutputStream` so far, is fully written to disk too. Here is an example of calling the Java `FileOutputStream` `flush()` method:

```
OutputStream outputStream = new FileOutputStream("c:\\data\\output-text.txt");

byte bytes =  new byte[]{1,2,3,4,5};

outputStream.write(bytes);

outputStream.flush()
```

### Closing a FileOutputStream

Like any other `OutputStream` a `FileOutputStream` instance needs to be closed after use. You do so by calling its `close()` method. Here is an example of closing a Java `FileOutputStream` by calling its `close()` method:

```
OutputStream outputStream = new FileOutputStream("c:\\data\\output-text.txt");

outputStream.write(123);

outputStream.close();
```

Unfortunately, if an exception is thrown during the `write()` call in the example above, that exception will cause the program flow to break before the `close()` method is called. Therefore it is better to close a Java `FileOutputStream` using the [Java try with resources](https://jenkov.com/java-exception-handling/try-with-resources.html) construct. Here is an example of closing a Java `FileOutputStream` using the try-with-resources construct:

```
try( OutputStream outputStream = new FileOutputStream("c:\\data\\output-text.txt") ) {
    outputStream.write(123);
}
```

Notice how the `FileOutputStream` is declared inside the parentheses following the `try` keyword. All resources declared inside these parentheses will be closed automatically once the program flow exits the `try` block, regardless of whether an exception is thrown or not. In other words, the `FileOutputStream` `close()` will be called automatically for you.

### Convert FileOutputStream to Writer

The Java `FileOutputStream` is a byte based stream. You can convert a `FileOutputStream` to a character based `Writer` using the [Java OutputStreamWriter](https://jenkov.com/tutorials/java-io/outputstreamwriter.html) class. Here is an example of converting a Java `FileOutputStream` to a `Writer` using `OutputStreamWriter`:

```
FileOutputStream outputStream       = new FileOutputStream("c:\\data\\output.txt");
Writer       outputStreamWriter = new OutputStreamWriter(outputStream);

outputStreamWriter.write("Hello World");
```

You can read more about how to use the `OutputStreamWriter` including how to set the character encoding to use when converting characters to bytes in my [OutputStreamWriter tutorial](https://jenkov.com/tutorials/java-io/outputstreamwriter.html).
