Java Files I/O
COP 2250/2210
This presentation contains adapted materials from different sources, including our
designated textbook, to be used for educational purposes only
Summary
• File Input and Output
• Writing Text To a File
• The PrintWriter Class
• Appending Text to a File
• Specifying a File Location
• Reading Data From a File
• Detecting The End of a File
• Static modifier
File Input and Output
• Reentering data all the time could get tedious for the user
• The data can be saved to a file.
• Files can be input files or output files
• Files:
• Files have to be opened.
• Data is then written to the file.
• The file must be closed prior to program termination
• In general, there are two types of files:
• binary
• text
Writing Text To a File
• To open a file for text output you create an instance
of the PrintWriter class.
PrintWriter outputFile = new PrintWriter("[Link]");
Pass the name of the file that you
wish to open as an argument to the
PrintWriter constructor.
Warning: if the file already exists, it will be erased and replaced with a new file.
The PrintWriter Class
• The PrintWriter class allows you to write data to a file using the print, println,and
printf methods, as you have been using to display data on the screen.
• Just as with the [Link] object, the println method of the PrintWriter class will place a
newline character after the written data.
• The print method writes data without writing the newline character.
Open the file.
import [Link].*;
PrintWriter outputFile = new PrintWriter("[Link]");
[Link]("Chris");
[Link]("Kathryn"); Use the println and printf methods
[Link]("Jean"); of PrintWriter to write text
[Link]();
Close the file.
Write data to the file.
import [Link]; // Needed for Scanner class
import [Link].*; // Needed for File I/O classes Since this method can potentially
"throw" an IOException (error), Java
public class FileWriteDemo requires that either (a) the exception
{ is handled in the method that caused
public static void main(String[] args) throws IOException it to occur, or (b) the method
{ terminates and throws the exception
String filename; // File name again. For now, we will use (b) by
String friendName; // Friend's name typing this statement in the method's
int numFriends; // Number of friends header.
Scanner keyboard = new Scanner([Link]); // Create a Scanner object for keyboard input.
// Get the number of friends.
[Link]("How many friends do you have? ");
numFriends = [Link]();
[Link](); // Consume the remaining newline character.
// Get the filename.
[Link]("Enter the filename: ");
filename = [Link]();
PrintWriter outputFile = new PrintWriter(filename); // Open the file.
// Get data and write it to the file.
for (int i = 1; i <= numFriends; i++)
{
// Get the name of a friend.
[Link]("Enter the name of friend " + "number " + i + ": ");
friendName = [Link]();
// Write the name to the file.
[Link](friendName);
}
// Close the file.
[Link]();
[Link]("Data written to the file.");
}
}
Appending Text to a File
• To avoid erasing a file that already exists, create a
FileWriter object in this manner:
FileWriter fw = new FileWriter("[Link]", true);
• Then, create a PrintWriter object in this manner:
PrintWriter pw = new PrintWriter(fw);
• Pass fw as parameter to PrintWriter. Example:
FileWriter fw = new FileWriter(filename, true);
PrintWriter outputFile = new PrintWriter(fw);
Specifying a File Location
• On a Windows computer, paths contain backslash (\)
characters
• Remember, if the backslash is used in a string literal, it
is the escape character so you must use two of them:
PrintWriter outFile =
new PrintWriter("C:\\[Link]");
If the backslash is in a String object then it will be handled properly.
(e.g. String filename = "C:\[Link]");)
Reading Data From a File
• You use the File class and the Scanner class to
read data from a file:
Pass the name of the file as an
argument to the File class
constructor.
File myFile = new File("[Link]");
Scanner inputFile = new Scanner(myFile);
Pass the File object as an
argument to the Scanner
class constructor.
Reading Data From a File
Once an instance of Scanner is created, data can be read
using the same methods that you have used to read keyboard
input (nextLine, nextInt, nextDouble, etc).
// Open the file.
File myFile = new File("[Link]");
Scanner inputFile = new Scanner(myFile);
// Read a line from the file.
String str = [Link]();
// Close the file.
[Link]();
Detecting the End of a File
The Scanner class's hasNext() method will return true if
another item can be read from the file
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Read until the end of the file.
while ([Link]())
{
String str = [Link]();
[Link](str);
}
[Link](); // close the file when done.
Reading Data From a File Example
import [Link]; // Needed for the Scanner
import [Link].*; // Needed for the File and IOException
public class FileReadDemo
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner([Link]); // Create a Scanner object for keyboard input
// Get the filename.
[Link]("Enter the filename: ");
String filename = [Link]();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while ( [Link]() ) // Read lines from the file until no more are left.
{
String friendName = [Link](); // Read the next name.
[Link](friendName); // Display the last name read.
}
[Link](); // Close the file.
}
}