Java 7 for Absolute Beginners

(nextflipdebug5) #1

C H A P T E R 8


151

Writing and Reading Files


Writing data to and reading data from files are common tasks for almost any kind of program. Even
simple games, such as our MineSweeper game, can benefit from storing information in a file and
retrieving it later. (MineSweeper could store the size of game the player last chose and keep track of the
best time for each size.) Java provides an extensive collection of classes and interfaces for dealing with
files (and associated objects such as directories and drives). The heart of it all is the aptly named and
often-used java.io.File class. “io” stands for input/output.


Working with File Objects


The first thing to know about working with java.io.File (I'll call it “File” from here on) objects is that a
File object is not a file. A File object in Java is an object that contains various bits of information about a
file. The distinction might seem meaningless, but it's very important. Consider the following bit of code:
File myFile = new File(); That code does not create an empty file on your system. Instead, it creates
an object within your program. For the sake of comparison, let's look at code that creates an empty file
on your system. Notice how we have to create a file, with the createNewFile() method, after we create
the file object.


■ Note To get the code in Listing 8-1 and Listing 8-2 to work, you must first create a directory called test on


your C drive.


Figure 8-1 shows my test directory (which I created just for this code) before running Listing 8-1. It's
not the most thrilling image, but I thought you should see the “before” image to go with Figure 8-2
(which shows the “after” image).


Java 7 for Absolute Beginners
© Jay Bryant 2012


J. Bryant,
Free download pdf