Java Reference
In-Depth Information
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 start-
ing point in the array, and the number of bytes to write.
The ByteWriter application in Listing 15.2 writes an integer array to a file output
stream.
LISTING 15.2
The Full Text of ByteWriter.java
1: import java.io.*;
2:
3: public class ByteWriter {
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
n
Lines 12 and 13 —Create a file output stream with the filename pic.gif in the
same folder as the ByteWriter.class file
n
Lines 14 and 15 —Use a for loop to cycle through the data array and write each
element to the file stream
n
Line 16 —Closes the file output stream
n
 
Search WWH ::




Custom Search