Chapter 4. File Streams
Until now, most of the examples in this book have used the streams System.in and System.out. These are convenient for examples, but in real life, you’ll more commonly attach streams to data sources like files and network connections. The java.io.FileInputStream
and java.io.FileOutputStream classes, which are concrete subclasses of java.io.InputStream and java.io.OutputStream, provide methods for reading
and writing data in files. What they don’t provide is file management, like finding out whether a file is readable or writable or moving a file from one directory to another. For that, you may want to flip forward to Chapter 17, which talks about the File class itself and the way Java works with files.
Reading Files
java.io.FileInputStream is a concrete subclass of java.io.InputStream. It provides an input stream connected to a particular file. FileInputStream has all the usual methods of input streams, such as read( ), available( ), skip( ), and close( ), which are used exactly as they are for any other input stream. FileInputStream( ) has three constructors, which differ only in how the file to be read is specified:
public FileInputStream(String fileName) throws IOException public FileInputStream(File file) throws FileNotFoundException public FileInputStream(FileDescriptor fdObj)
The first constructor uses a string containing the name of the file. The second constructor uses a java.io.File object. The third constructor uses a java.io.FileDescriptor ...