Java Streams  «Prev 

Java Streams - End-of-Stream Flag

If read() encounters the end-of-stream, it returns -1 instead. You use this as a flag to watch for the end-of-stream.
int[] b = new int[10];
for (int i = 0; i < b.length; i++) {
  int datum =;
  if (datum  == -1) break;
  b[i] = datum;

Read PDF file and write to another File

The following is an example of reading a PDF file and writing it to another file. A PDF file never contains just character data. Even if a PDF file contains only characters, it also contains formatting information, so as a whole, a PDF file cannot be considered character data. You can also use the PDF format for an image file, if you have any doubts.
Note: Even though FileInputStream and FileOutputStream can be used to write character data, you should not use them to do so. Unlike byte I/O streams, character streams take into account a user's charset and work with Unicode characters, which are bettersuited for character data.
To read and write to separate PDF files, you need objects of Stream and that can connect to these input and output PDF files. You need to call at least one method on FileInputStream to read data, and one method on FileOutputStream to write data. Previously, I mentioned that InputStream and OutputStream define methods read() and write() to read and write a single byte of data, respectively. The following listing contains an example of these methods.
Figure 3.2: Using FileInputStream and FileOutputStream to read and write bytes

Are you wondering why you need to create a variable of type int to read byte data from a file in the preceding code? When a stream exhausts itself and no data can be read from it, method read() returns -1, which cannot be stored by a variable of type byte.
The code at 1) and 2) instantiates FileInputStream and FileOutputStream. The constructors used in this code accept the filenames as String objects. You can also pass the constructors' instances of class File or String. At 3) , you declare a variable of type int to store the byte data you read from the file. At 4), you call, which reads and returns a single byte from the underlying file Sample.pdf. When no more data can be read from the input file, method read() returns -1, and this is when the while loop ends its execution. At f, you write a single byte of data to another file by using out, an instance of FileOutputStream.