Java Reference
In-Depth Information
java.io.InputStream
javo.io.FileInputStream
+FileInputStream(file: File)
+FileInputStream(filename: String)
Creates a FileInputStream from a File object.
Creates a FileInputStream from a file name.
F IGURE 17.6
FileInputStream inputs a stream of bytes from a file.
java.io.OutputStream
java.io.FileOutputStream
+FileOutputStream(file: File)
+FileOutputStream(filename: String)
+FileOutputStream(file: File, append: boolean)
+FileOutputStream(filename: String, append: boolean)
Creates a FileOutputStream from a File object.
Creates a FileOutputStream from a file name.
If append is true, data are appended to the existing file.
If append is true, data are appended to the existing file.
F IGURE 17.7
FileOutputStream outputs a stream of bytes to a file.
Almost all the methods in the I/O classes throw java.io.IOException . Therefore, you
have to declare to throw java.io.IOException in the method or place the code in a try-
catch block, as shown below:
IOException
Declaring exception in the method
public static void main(String[] args)
throws IOException {
// Perform I/O operations
Using try-catch block
public static void main(String[] args) {
try {
// Perform I/O operations
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
Listing 17.1 uses binary I/O to write ten byte values from 1 to 10 to a file named temp.dat
and reads them back from the file.
L ISTING 17.1
TestFileStream.java
1 import java.io.*;
2
3 public class TestFileStream {
4 public static void main(String[] args) throws IOException {
5 try (
6 // Create an output stream to the file
7 FileOutputStream output = new FileOutputStream( "temp.dat" );
8 ) {
9
import
output stream
// Output values to the file
10
for ( int i = 1 ; i <= 10 ; i++)
11
output.write(i);
output
12 }
13
14
try (
 
 
Search WWH ::




Custom Search