Working with Input and Output in Java - File Output Streams (Page 5 of 5 )
A file output stream can be created with the FileOutputStream(String) constructor. The usage is the same as the FileInputStream(String) constructor, so you can specify a path along with a filename.
You have to be careful when specifying the file associated with an output stream. If it's the same as an existing file, the original will be wiped out when you start writing data to the stream.
You can create a file output stream that appends data after the end of an existing file with the FileOutputStream(String, boolean) constructor. The string specifies the file, and the Boolean argument should equal true to append data instead of overwriting existing data.
The file output stream's write(int) method is used to write bytes to the stream. After the last byte has been written to the file, the stream's close() method closes the stream.
To write more than one byte, the write(byte[], int, int) method can be used. This works in a manner similar to the read(byte[], int, int) method described previously. The arguments to this method are the byte array containing the bytes to output, the starting point in the array, and the number of bytes to write.
The WriteBytes application in Listing 15.2 writes an integer array to a file output stream.
Listing 15.2 The Full Text of
WriteBytes.java 1: import java.io.*;
2:
3: public class WriteBytes {
4: public static void main(String[] arguments) {
5: int[] data = { 71, 73, 70, 56, 57, 97, 13, 0,
12, 0, 145, 0,
6: 0, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
0, 0, 44, 0,
7: 0, 0, 0, 13, 0, 12, 0, 0, 2, 38, 132, 45,
121, 11, 25,
8: 175, 150, 120, 20, 162, 132, 51, 110, 106,
239, 22, 8,
9: 160, 56, 137, 96, 72, 77, 33, 130, 86, 37,
219, 182, 230,
10: 137, 89, 82, 181, 50, 220, 103, 20, 0, 59
};
11: try {
12: FileOutputStream file = new
13: FileOutputStream("pic.gif");
14: for (int i = 0; i < data.length; i++)
15: file.write(data[i]);
16: file.close();
17: } catch (IOException e) {
18: System.out.println("Error -- " +
e.toString());
19: }
20: }
21: }
The following things are taking place in this program:
Lines 5–10—Create an integer array called data with 66 elements
Lines 12 and 13—Create a file output stream with the filename pic.gif in the same folder as the WriteBytes.class file
Lines 14 and 15—Use a for loop to cycle through the data array and write each element to the file stream
Line 16—Closes the file output stream
After you run this program, you can display the pic.gif file in any Web browser or graphics-editing tool. It's a small image file in the GIF format, as shown in Figure 15.1.
Figure 15.1 The pic.gif file (enlarged).