Working with text files
in Java
BufferedReader
and
PrintWriter
Reading text from a file
BufferedReader inFile;
String lineOfText;
// open the file
inFile = new BufferedReader(
new FileReader("[Link]"));
// read the file
lineOfText = [Link]();
…
// close the file
[Link]();
Writing text to a file
PrintWriter outFile;
String name = "Bob";
// open the file
outFile = new PrintWriter(
new FileWriter("[Link]"));
// write some lines to the file
[Link]("Hello, ");
[Link](name);
// close the file
[Link]();
Reading all lines of a file
readLine() returns null whenever
an attempt is made to read an empty file
previous calls to readLine() have read all the lines of
the file, and we have reached the end of the file.
We can use this fact in a while loop to read all
the lines of a file:
while ((lineOfText = [Link]()) != null)
{
/* process lineOfText */
}
[Link]
This is the first line.
This is the second line.
This is the third line.
Example: [Link]
import [Link].*; // File classes
public class UseFile
{
public static void main(String[] args)
throws IOException
{
PrintWriter outFile; // Output data file
BufferedReader inFile; // Input data file
String lineOfText; // String to hold
// data lines
[Link]
// Prepare input and output files
inFile = new BufferedReader(
new FileReader("[Link]"));
outFile = new PrintWriter(
new FileWriter("[Link]"));
// Read lines from [Link]
while ((lineOfText = [Link]()) != null)
{
// write line to console
[Link](lineOfText);
// write line of outFile
[Link](lineOfText);
}
[Link]
[Link](); // finished reading
[Link](); // Finished writing
}
}
Output of UseFile
[Link]
This is the third line.
This is the second line.
This is the first line.
Reading from the console
Reading from the console is just like
reading from a text file.
The difference is in how the
BufferedReader object is created.
To create a BufferedReader for reading
from the console (keyboard), do this:
BufferedReader inData =
new BufferedReader(
new InputStreamReader([Link]));
Reading from the console
BufferedReader inData =
new BufferedReader(
new InputStreamReader([Link]));
String name, lineOfText;
int age;
[Link]("Enter your name: ");
name = [Link]();
[Link]("Enter your age: ");
lineOfText = [Link]();
age = [Link]([Link]());