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
19.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
19.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
java.io.IOException
to throw in the method or place the code in a try-
catch block, as shown below:
IOException
Declaring exception in the method
Using try-catch block
public static void
main(String[] args)
public static void
main(String[] args) {
throws IOException
{
try
{
// Perform I/O operations
// Perform I/O operations
}
}
catch
(IOException ex) {
ex.printStackTrace();
}
}
Listing 19.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
19.1
TestFileStream.java
1
import
java.io.*;
2
3
public class
TestFileStream {
4
import
throws
IOException
public static void
main(String[] args)
{
5
// Create an output stream to the file
FileOutputStream output =
new
FileOutputStream(
"temp.dat"
);
output stream
6
7
8
// Output values to the file
9
for
(
int
i =
1
; i <=
10
; i++)
output.write(i);
output
10
11
12
// Close the output stream
13
14
output.close();