- MHS Comp Sci

Download Report

Transcript - MHS Comp Sci

FILE I/O
Starring: Scanner
Co-Starring: useDelimiter
LECTURE:
FILE I/O
Objective:
Learn how to process data files, one line at
a time, one field at a time.
Read from a file and Write to a file.
Use Scanner and PrintWriter classes for file
processing.
Resources:
Lambert Fundamentals, 3rd Edition
p.127-129 & 74-76
Java 1.5 Program Design p.266-271
Processing files is a central element in
robust application development.
We will learn the Java way of file
processing and then learn how to use
predefined classes ( Scanner and File ) to
make file processing much simpler.
The sample project, File IO.java, has static
functions that illustrate file processing
using the following options:
1.
2.
3.
read a file one line at a time
write a new file
read a file one word at a time
Initial Steps:
Create an Instance of the File class that
allows you to hold the information about
the file you wish to process
// Create an Instance of the File Class
// java.io
File file = new File("file.txt");
PUT THE TEXT FILE (.txt) IN THE PROJECT FOLDER !!!
Create an Instance of the Scanner class that allows you to
PROCESS the file
This step also opens the file
// Create an Instance of the Scanner Class and
// ASSOCIATE it with the FILE
// To read in the fields of the FILE
// OPENS the FILE "file.txt"
Scanner scanner = new Scanner(file);
// Create an Instance of the PrintWriter Class to WRITE out
// an FILE
PrintWriter pw = new PrintWriter(file);
Read a file one line at a time:
// read in a file one line at a time
// 1. read a file one line at a time ---//DEFAULT WHITESPACE DELIMITER
while (scanner.hasNext())
{
System.out.println(scanner.nextLine());
}
scanner.close();
Read a file one word at a time:
//USE the useDelimeter Method of the Scanner
//class to determine what constitutes a new word
scanner = new Scanner(file);
scanner.useDelimiter(",");
while (scanner.hasNext())
{
System.out.println(scanner.next());
}
scanner.close();
You can also read in data as a number or a
character:
System.out.println("xxx" + scanner.nextLine());
// String; uses new line as a delimiter
System.out.println(scanner.next()); // String; uses
//space as delimiter by default
System.out.println(scanner.nextInt() + 1); // int
System.out.println(scanner.nextDouble() * 2); //
// double
System.out.println(scanner.next().charAt(0)); //
//nextChar()
Write out to a FILE:
// 3. write a new file
// Create an Instance of the PrintWriter Class to WRITE
// out an FILE
file = new File("fileout.txt");
PrintWriter pw = new PrintWriter(file);
pw.println("NEW LINE FIRST IN OUT FILE");
pw.println("NEW LINE SECOND IN OUT FILE");
pw.println("20 40 56 45");
pw.print("34,");
pw.print("72,");
pw.close();
Projects: Process Numbers in a File
Unique Name Merge
Correct Answers
Modify Student File
Average Student Answers
Create a Writer Class
MyTutor
AN ELECTRONIC QUIZ FOLLOWS