Chapter 9. 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 a hard disk (and all the operating system-dependent filesystem types), a floppy or zip drive, a CD-ROM, and others. For now, they’re just files.

Correcting Misconceptions

Java’s approach to input/output is sufficiently different from that of older languages (C, Fortran, Pascal) that people coming from those languages are often critical of Java’s I/O model. I can offer no better defense than that provided in the preface to Elliotte Rusty Harold’s book Java I/O :

Java is the first programming language with a modern, object-oriented approach to input and output. Java’s I/O model is more powerful and more suited to real-world tasks than any other major language used today. Surprisingly, however, I/O in Java has a bad reputation. It is widely believed (falsely) that Java I/O can’t handle basic tasks that are easily accomplished in other languages like C, C++, and Pascal. In particular, it is commonly said that:

-- I/O is too complicated for introductory students; or, more specifically, there’s no good way to read a number from the console.

-- Java can’t handle basic formatting tasks like printing PI with three decimal digits of precision.

[Rusty’s book shows] that not only can Java handle these ...

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