O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Files and Streams

One of the commonly used classes in the java.io package is File. This class is somewhat misleadingly named, as it represents a filename (or directory name), rather than a file itself. Because files (and directories) have different naming conventions under different operating systems, Java provides the File class to try to hide some of those differences. The File class also defines various methods for operating on files as a whole: deleting files, creating directories, listing directories, querying the size and modification time of a file, and so on.

While the File class provides methods to manipulate directories and the files within those directories, it doesn’t provide any methods that manipulate the contents of the files. In other words, it doesn’t provide any way to read or write the bytes or characters that are contained in files. In Java, sequential file I/O is performed through a stream abstraction. (Random-access file I/O is performed with the RandomAccessFile class, but sequential I/O is much more common.)

A stream is simply an object from which data can be read sequentially or to which data can be written sequentially. The bulk of the java.io package consists of stream classes: there are 40 of them. InputStream and OutputStream and their respective subclasses are objects for reading and writing streams of bytes, whereas Reader and Writer and their subclasses are objects for reading and writing streams of Unicode characters. In addition to these stream ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required