Java Reference
In-Depth Information
Reading a File's Content
Before we can get much further, we first need a file that contains some content. So, let's set up a test
case. Copy the content from Listing 8-12 (a few lines from Shakespeare's play, Hamlet ) into a text file
called Hamlet.txt and put the file in your C:\test directory.
Listing 8-12. Original contents of Hamlet.txt
To sleep: perchance to dream: ay, there's the rub;
For in that sleep of death what dreams may come
When we have shuffled off this mortal coil,
Must give us pause: there's the respect
That makes calamity of so long life
(Feel free to use your own favorite bit of content if you don't like mine. For our purposes right now,
all we need is some text.)
Now that we have a file with some content, we can read that content into memory with a program.
To read a file's content, a Java developer generally reaches for a FileInputStream object. Listing 8-13
shows a simple program to read a file and repeat the contents in the console:
Listing 8-13. Putting hamlet.txt in the console.
package com.apress.java7forabsolutebeginners.examples;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
// Specify the file
String fileName = "C:" + File.separator + "test"
+ File.separator + "Hamlet.txt";
File hamletFile = new File(fileName);
// Set up a byte array to hold the file's content
byte[] content = new byte[0];
try {
// Create an input stream for the file
FileInputStream hamletInputStream = new FileInputStream(hamletFile);
// Figure out how much content the file has
int bytesAvailable = hamletInputStream.available();
// Set the content array to the length of the content
content = new byte[bytesAvailable];
// Load the file's content into our byte array
hamletInputStream.read(content);
// Close the stream
hamletInputStream.close();
} catch (FileNotFoundException fnfe) {
System.out.println("Couldn't find a file called " + fileName);
Search WWH ::




Custom Search