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 ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.