Chapter 10. Input and Output

Introduction

Most programs need to interact with the outside world, and one common way of doing so is by reading and writing files. Files are normally on some persistent medium such as a disk drive, and, for the most part, we shall happily ignore the differences between files on a hard disk (and all the operating system-dependent filesystem types), a USB drive or SD card, a DVD-ROM, and others. For now, they’re just files. And, like most other languages and OSes, Java extends the “reading and writing” model to network (socket) communications, which we’ll touch on in Chapters 13 and 16.

Java provides many classes for input and output; they are summarized in Figure 10-1. This chapter covers all the normal input/output operations such as opening/closing and reading/writing files. Files are assumed to reside on some kind of file store or permanent storage. Distributed filesystems such as Sun’s Network File System (NFS, common on Unix and available for Windows), SMB (the Windows network filesystem, available for Unix via the open source Samba program), and FUSE (Filesystem in User SpacE, implementations for most Unix/Linux systems) are assumed to work “just like” disk filesystems, except where noted.

The Formatter and Scanner classes provide formatting and scanning, of course. Formatter allows many formatting tasks to be performed either into a String or to almost any output destination. Scanner parses many kinds of objects, again either from a String or from ...

Get Java Cookbook, 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.