Introduction to Using Text Files
Up until now, most of the data you have worked with in Java was likely "hard-coded" directly into your programs. But what happens if you have thousands of data points, like a list of every city's temperature or a library's book catalog? You cannot type all of that into your source code! This is where text files come in. In this chapter, you will learn how to connect your Java program to an external file to read and process large amounts of information efficiently.
Reading from files is a key part of Unit 4: Data Collections because it is the primary way we get data into the arrays and ArrayLists we have been studying.
The File Class: Identifying the Source
Before you can read data, Java needs to know where that data is located. Think of the File class as a "map" or a "pointer" to a specific location on your computer's storage.
To create a reference to a file, we use the File constructor:
\( File \ myFile = new \ File("data.txt"); \)
Key Points about the File Class:
- The \( pathname \) (like "data.txt") is a String that tells Java the name and location of the file.
- Creating a \( File \) object does not actually open the file or read its contents yet; it just sets up the connection.
The Scanner Class: Reading the Content
While the \( File \) class finds the file, the Scanner class is the tool that actually reads the data inside it. You might have seen \( Scanner \) used for keyboard input in the past, but in AP Computer Science A, we focus on using it to read from a \( File \) object.
How to set it up:
\( Scanner \ input = new \ Scanner(myFile); \)
Once the scanner is linked to the file, it acts like a pointer that moves through the text, one piece at a time.
Essential Scanner Methods
The Scanner "tokenizes" the file, meaning it breaks the text into small pieces (tokens) separated by whitespace (spaces, tabs, or new lines).
- \( next() \): Reads the next token as a \( String \).
- \( nextInt() \): Reads the next token and converts it to an \( int \).
- \( nextDouble() \): Reads the next token and converts it to a \( double \).
- \( nextBoolean() \): Reads the next token and converts it to a \( boolean \).
- \( nextLine() \): Reads everything from the current position to the end of the current line.
- \( close() \): Closes the scanner. It is good practice to close the scanner once you are finished to free up system resources.
Note: For the AP Exam, avoid using \( nextLine() \) in combination with methods like \( nextInt() \) or \( nextDouble() \) on the same file, as this can lead to unexpected behavior.
The Guard: Using hasNext()
If you try to call \( nextInt() \) but the scanner has already reached the end of the file, your program will crash with an error. To prevent this, we use the \( hasNext() \) method.
\( hasNext() \) returns \( true \) if there is at least one more token in the file, and \( false \) if the end has been reached. This is perfect for use in a \( while \) loop!
Step-by-Step Logic for Reading a File:
1. Create a \( File \) object.
2. Pass that \( File \) object into a \( Scanner \).
3. Use a \( while(input.hasNext()) \) loop to keep reading as long as there is data.
4. Inside the loop, use \( next() \), \( nextInt() \), or \( nextDouble() \) to grab the data.
5. \( close() \) the scanner when done.
Example Pattern:
Assume "numbers.txt" contains: 10 20 30
\( File \ f = new \ File("numbers.txt"); \)
\( Scanner \ s = new \ Scanner(f); \)
\( while(s.hasNext()) \ \{ \)
\( int \ val = s.nextInt(); \)
\( System.out.println(val); \)
\( \} \)
\( s.close(); \)
Quick Review: Important Distinctions
Did you know? Even though a file might look like a list of numbers to you, the computer initially sees them as characters. Methods like \( nextInt() \) are special because they automatically perform the "conversion" from text characters to actual numeric data types.
Common Mistake to Avoid:
Don't forget that \( hasNext() \) only checks if data exists; it does not move the scanner forward. Only the "next" methods (\( next() \), \( nextInt() \), etc.) actually move the "pointer" to the next piece of data.
Key Takeaway
The \( File \) class identifies the resource, and the \( Scanner \) class provides the methods to extract data. Using a \( while \) loop with \( hasNext() \) ensures that you process the entire file without running into errors by trying to read past the end of the data.
For more information on what to do with this data once you've read it, see the chapters on Array Traversals and ArrayList Methods.