Java Reference
In-Depth Information
it doesn't already exist, and if it does exist, the contents are overwritten. Here's how you can open a file
specified by a Path object fileOut to append data to it if it already exists:
OutputStream fileOut = Files.newOutputStream(path, CREATE, APPEND);
The WRITE option is inferred because the method only creates OutputStream objects. Of course, it would
be better to use a BufferedOutputStream object to write the file because this would make the output oper-
ations more efficient. You can create one like this:
Path file = Paths.get("D:/Junk/fibonnaci.bin");
BufferedOutputStream fileOut = new BufferedOutputStream(
Files.newOutputStream(file, CREATE, APPEND));
To create a buffered stream, you just pass the OutputStream object returned by the newOutputStream()
method to the BufferedOutputStream constructor.
The newOutputStream() method can throw an IOException if an error occurs so it needs to be called
in a try block. The stream classes implement the AutoCloseable interface so you can use a try block with
resources to automatically close any stream when you are done with it.
A BufferedOutputStream object provides two write() methods:
write(int b) writes a single byte, b , to the internal buffer,.
write(byte[] b, int offset, int length) writes length bytes from the byte array, b , start-
ing at index position offset to the internal buffer.
• Both methods can throw IOException . The internal buffer is automatically flushed (written to the
stream) when it is full. You can also call the flush() method explicitly to have the buffer contents
written to the stream.
Note that flushing the stream does not guarantee that the data is written to the file at that point. Flushing
the stream hands over the data to the output operation provided by your operating system and this has its
own internal buffers. You see later in this chapter how you can force data to be written to the file.
TRY IT OUT: Writing a File via a Buffered Stream
This example generates some binary integer values and writes them to a file:
import java.nio.file.*;
import java.nio.*;
import java.io.*;
public class StreamOutputToFile {
public static void main(String[] args) {
final int count = 50;
// Number of
values
long[] fiboNumbers = {0L,0L};
// Array of 2
elements
int index = 0;
// Index to
Search WWH ::




Custom Search