Vous êtes sur la page 1sur 12

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("infile.txt"));
// read the file
lineOfText = inFile.readLine();

// close the file
inFile.close();
Writing text to a file
PrintWriter outFile;
String name = "Bob";
// open the file
outFile = new PrintWriter(
new FileWriter("outfile.txt"));
// write some lines to the file
outFile.print("Hello, ");
outFile.println(name);

// close the file


outFile.close();
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 = inFile.readLine()) != null)


{
/* process lineOfText */
}
infile.txt
This is the first line.
This is the second line.
This is the third line.
Example: UseFile.java
import java.io.*; // 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
UseFile.java

// Prepare input and output files


inFile = new BufferedReader(
new FileReader("infile.txt"));
outFile = new PrintWriter(
new FileWriter("outfile.txt"));
// Read lines from infile.dat
while ((lineOfText = inFile.readLine()) != null)
{
// write line to console
System.out.println(lineOfText);
// write line of outFile
outFile.println(lineOfText);
}
UseFile.java
intFile.close(); // finished reading
outFile.close(); // Finished writing
}
}
Output of UseFile
outfile.txt

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(System.in));
Reading from the console
BufferedReader inData =
new BufferedReader(
new InputStreamReader(System.in));
String name, lineOfText;
int age;
System.out.print("Enter your name: ");
name = inData.readLine();
System.out.print("Enter your age: ");
lineOfText = inData.readLine();
age = Integer.parseInt(lineOfText.trim());

Vous aimerez peut-être aussi