Download COMP 110

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Announcements
Program 5 Milestone 1 was due today
Program 4 has been graded
1
COMP 110: Spring 2009
Today in COMP 110
Review Exceptions
Basic File I/O
Programming Demo
2
COMP 110: Spring 2009
Review
Exceptions
3
COMP 110: Spring 2009
Exceptions
An exception is an object that signals
the occurrence of an unusual
(exceptional) event during program
execution
Exception handling is a way of
detecting and dealing with these
unusual cases in principled manner i.e.
without a run-time error or program
crash
4
COMP 110: Spring 2009
The try Block
A try block contains the basic algorithm for
when everything goes smoothly
Try blocks will possibly throw an exception
Syntax
try {
Code_To_Try
}
Example
try {
average = scoreSum/numGames;
}
5
COMP 110: Spring 2009
The catch Block
The catch block is used to deal with any
exceptions that may occur
This is your error handling code
Syntax
catch(Exception_Class_Name Catch_Block_Parameter) {
Process_Exception_Of_Type_Exception_Class_Name
}
Possibly_Other_Catch_Blocks
Example
catch(ArithmeticException e) {
System.out.println(e.getMessage());
System.out.println("Cannot compute average for 0 games");
}
6
COMP 110: Spring 2009
Example
Using Exception Handling (try/catch blocks)
int score = keyboard.nextInt();
int scoreSum = 0;
int numGames = 0;
while(score >= 0) {
scoreSum += score;
numGames++;
score = keyboard.nextInt();
}
double average = 0;
try {
average = scoreSum/numGames;
}
catch(ArithmeticException e) {
System.out.println(e.getMessage());
System.out.println("Cannot compute average for 0 games");
}
7
COMP 110: Spring 2009
Files
Your music, pictures, videos, even your
Java programs are stored on your
computer in files
Files can also be used to store input for
a program, or a program’s output
8
COMP 110: Spring 2009
Streams
Writing to & reading from files is done using a
stream
A stream is a flow of data
This data might be characters, numbers or bytes of binary
digits
Data that flows INTO your program is called
an input stream
Data that flows OUT of your program is called
an output stream
9
COMP 110: Spring 2009
Streams
Input Stream
Output Stream
Keyboard
Input Stream
CD
10
Monitor
Output Stream
Program
Hard drive
COMP 110: Spring 2009
Stream Class
In Java, streams are objects of special
stream class
Scanner objects are input streams
We’ve used the Scanner class to read data from
the keyboard
System.out is an output stream
We use it to print data out to screen
11
COMP 110: Spring 2009
File I/O
File I/O stands for File Input/Output
Why use files for input/output?
Permanent data storage
Easy to read in large amount of data
• We can also read it in repeatedly
Easy to output large amounts of data that can be
analyzed later
12
COMP 110: Spring 2009
Text Files vs Binary Files
All files are stored as binary digits (bits)
In some cases this data is interpreted as
text (text files)
Your Java files
Text files can be easily read/edited by humans
All other files are binary files
Your music & picture files
Binary files cannot be easily read/edited by
humans
13
COMP 110: Spring 2009
Creating a Text File
The PrintWriter class is provided by Java
to aid in creating and writing text files
Need to import from java.io
Before we can write to a text file, we
need to connect to an output stream
This is essentially opening the file, which allows us
to write to it
All files have a name, such as out.txt, that we use
when opening the file
14
COMP 110: Spring 2009
Opening a Text File
//need to import java.io.PrintWriter
//& java.io.FileNotFoundException
String fileName = "out.txt";
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(fileName);
}
catch(FileNotFoundException e) {
System.out.println("Error opening file " + fileName);
System.exit(0);
}
15
COMP 110: Spring 2009
Opening a Text File
outputStream = new PrintWriter(fileName);
Calls the constructor of the PrintWriter class
Opens the text file with the name fileName ("out.txt")
If the file already exists, its contents are overwritten
If the file doesn’t exist, an empty file with that name is
created
Since the constructor might throw a
FileNotFoundException, we must enclose it in
a try block
Also need a corresponding catch block to catch the exception
16
COMP 110: Spring 2009
Writing to a Text File
Once the file is open, we can write to it
The PrintWriter class has methods print
& println that work just like methods in
System.out
Data is written to the file instead of to screen
Calls to these methods do not have to be within a
try block
outputStream.println("I’m writing to a file!");
outputStream.print("Another message!");
17
COMP 110: Spring 2009
Buffering
When you write to a file, the data may
not immediately reach its destination
This is because of buffering
The output stream will wait until it has collected a
large amount of data to write before it writes
anything to the file itself
This is done for efficiency
18
COMP 110: Spring 2009
Closing a Text File
Once you’re finished writing to the file you
should disconnect the stream from the file
itself
This is done using the close method
outputStream.close(); //close the file
Calling the close() method ensures that any
remaining data is written out to the file
19
COMP 110: Spring 2009
Example: Writing to a File
import java.io.*;
public class TextFileOutput {
public static void main(String[] args) {
String fileName = "out.txt";
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(fileName);
}
catch(FileNotFoundException e) {
System.out.println("Error opening file " + fileName);
System.exit(0);
}
//print the numbers 0-9 to the file one on each line
for(int i = 0; i < 10; i++) {
outputStream.println(i);
}
20
}
}
outputStream.close(); //close the file
COMP 110: Spring 2009
Summary: Writing to a File
Open the file
Create a PrintWriter object
• Pass the name of the file you want to write to the constructor
Use try/catch blocks to catch a possible
FileNotFoundException
Write to the file
Use the print/println methods of the PrintWriter object you
created
Close the file
21
COMP 110: Spring 2009
Reading from a Text File
We can read from a text file using an
object of the Scanner class
Recall, we have used the scanner class to read
input from the keyboard, as in:
Scanner keyboard = new Scanner(System.in);
We can create a scanner object to read
from a file in the following way
String fileName = "in.txt";
Scanner inputFile = new Scanner(new File(fileName));
22
COMP 110: Spring 2009
Opening a File for Reading
The Scanner class constructor can also
throw a FileNotFoundException
We must enclose it in a try block
String fileName = "in.txt";
Scanner inputFile = null;
try {
inputFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException e) {
System.out.println("Error opening file " + fileName);
System.exit(0);
}
23
COMP 110: Spring 2009
Reading from a Text File
All methods of the Scanner class we
have used previously can also be used
to read from a text file
nextInt(), nextDouble(), nextLine(), etc
The Scanner class also has methods to
determine whether more input data
remains in the file
hasNext(), hasNextDouble(), hasNextInt(),
hasNextLine() etc.
24
COMP 110: Spring 2009
Read a File & Print to Screen
import java.util.Scanner;
import java.io.*;
public class TextFileInput {
public static void main(String[] args) {
String fileName = "in.txt"; //the name of the file we want to open
Scanner inputFile = null;
try {
inputFile = new Scanner(new File(fileName)); //open the file
}
catch(FileNotFoundException e) {
System.out.println("Error opening file " + fileName);
System.exit(0);
}
while(inputStream.hasNextLine()) {
String line = inputStream.nextLine(); //read a line of text from the file
System.out.println(line); //print the line of text to screen
}
inputFile.close(); //close the file
}
}
25
COMP 110: Spring 2009
Closing an Input File
One you’re finished reading from a text
file, you should close the stream
Allowing you to write to it later etc
This is done using the close method
inputFile.close();
26
COMP 110: Spring 2009
Summary: Reading from a File
Open the file
Create a Scanner object
Use try/catch blocks to catch a possible
FileNotFoundException
Read from the file
Use the methods of the Scanner object you
created
Close the file
27
COMP 110: Spring 2009
The Class File
Java provides the class File as a way of
representing file names
A string such as "out.txt" may be a file
name, but Java treats it as any other
String object
Passing "out.txt" to the constructor of
the class file allows us to treat this as a
file name in Java
28
COMP 110: Spring 2009
Using the Class File
The class File has a constructor that
takes in the name of the file
Example
File outFile = new File("out.txt");
File inFile = new File("in.txt");
29
COMP 110: Spring 2009
Using the Class File
The class File also defines several useful methods for working w/ files
public boolean canRead()
•
Tests whether the program can read from the file
public boolean canWrite()
•
Tests whether the program can write to the file
public boolean delete()
•
Attempts to delete the file. Returns true on success
public boolean exists()
•
Tests whether the file currently exists
public String getName()
•
Returns the name of the file
public String getPath()
•
Returns the path name of the file
public long length()
•
30
Returns the length of the file in bytes
COMP 110: Spring 2009
Using Path Names
When specifying a file name such as "out.txt",
the file is assumed to be in the same directory
as your program
We can refer to a file in a different directory
using a path name instead of just the file
name
Example
"C:\\COMP110\\out.txt"
31
COMP 110: Spring 2009
Using Path Names
A full path name is a complete path
name starting at the root directory
e.g. "C:\\COMP110\\out.txt"
A relative path name is a path to the
file starting at the directory containing
your program
e.g. "files\\out.txt"
32
COMP 110: Spring 2009
Using Path Names
Why use two backslashes (\\) when
specifying file paths in Java?
e.g. "C:\\COMP110\\out.txt"
Recall that backslash is the escape
character in Java
'\n' – newline, '\t' – tab, etc
"\\" in a string means a single backslash
33
COMP 110: Spring 2009
Using File Paths
To get around having to use two
backslashes, we can use UNIX-style file
paths
e.g. "C:/COMP110/out.txt"
This works on both Windows and UNIX!
34
COMP 110: Spring 2009
File Names
What if we don’t know the name of the
file when writing the program?
Ask the user for the name of the file!
35
COMP 110: Spring 2009
Programming Demo
Write a program that searches a file of
numbers and displays the largest
number, smallest number and average
of all numbers in the file
Write the statistics out to a separate file
Ask the user for the names of the
input/output files
36
COMP 110: Spring 2009
Programming Demo
Programming
37
COMP 110: Spring 2009
Friday
Recitation
Short lab
Work on Program 5
38
COMP 110: Spring 2009