Download Chapter 9 - Lyle School of Engineering

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
CSE 1341
File I/O
Exception Handling
Introduction to File Processing
• Data stored in variables and arrays is temporary.
CPU
Control
Unit
Main
Memory
Input
Devices
ALU
Registers
Secondary
Memory
Output
Devices
• For long-term retention of data, even after the programs that
create the data terminate, computers use files.
• Computers store files on secondary storage devices such as
hard disks, optical disks, flash drives and magnetic tapes.
CPU
Control
Unit
Main
Memory
Input
Devices
ALU
Registers
Secondary
Memory
Output
Devices
Introduction to File Processing
• Data maintained in files is persistent data because it exists
beyond the duration of program execution.
• File processing is a subset of Java’s stream-processing
capabilities, which include reading from and writing to
memory, files and network connections.
Files and Streams
• Java views each file as a sequential stream of bytes.
• Every operating system provides a mechanism to determine the end of a
file, such as an end-of-file marker or a count of the total bytes in the file
that is recorded in a system-maintained administrative data structure.
• A Java program processing a stream of bytes simply receives an indication
from the operating system when it reaches the end of the stream—the
program does not need to know how the underlying platform represents
files or streams.
Text Files / Character Streams
• Streams that input and output characters are known as
character-based streams, representing data as a sequence of
characters.
• Files that are created using character-based streams are
referred to as text files.
• Text files can be read by any text editor.
Binary Files / Byte-based Streams
• Streams that input and output bytes are known as byte-based
streams, representing data in its binary format.
• Files that are created using byte-based streams are referred to
as binary files.
• Binary files are read by programs that understand the specific
content of the file and the ordering of that content.
Reading Data from a
Sequential-Access Text File
• There are several ways to initialize a Scanner.
• When reading data from the user at the keyboard, we
initialize a Scanner with the System.in object, which
represents a stream that is connected to the keyboard.
• To read data from a file, you must initialize the Scanner with a
File object.
• If the file cannot be found, an exception (of type
FileNotFoundException) occurs and the program terminates
immediately.
.
Exception Handling
• Definition: An Exception is an event that occurs during the
execution of a program that disrupts the normal flow of
instructions.
• Throwing an Exception is when the method creates an
exception object and hands it off to the runtime system –
usually in response to some type of error.
The Catch or Specify Requirement
• Code that might throw certain exceptions must be
enclosed by either of the following:
– A try statement that catches the exception.
– A method that specifies that it can throw the exception.
Throwable
Exception
Checked
Unchecked
Error
Exception Handling – the 10% You Need To Know
It all comes down to wrapping your code in try-catch-finally
blocks to handle the throwable exceptions or specifying
throws in the method header.
try {
} catch (ExceptionType name) {
} finally {
}
And/Or
public void myMethod() throws myException { … }
Catching and Handling Exceptions
• Three exception handler components
try {
} catch (ExceptionType name)
{
} finally {
}
Catching and Handling Exceptions:
The try block
• Enclose the code that might throw an exception within a
try block.
• If an exception occurs within the try block, that exception
is handled by an exception handler associated with it.
• To associate an exception handler with a try block, you
must put a catch block after it.
try {
}
20
20
Catching and Handling Exceptions:
The catch blocks
• You associate exception handlers with a try block by providing one or
more catch blocks directly after the try.
• Each catch block is an exception handler and handles the type of
exception indicated by its argument.
• The ExceptionType declares the type of exception that the handler can
handle and must be the name of a class that inherits from the
Throwable class.
• The catch block contains code that is executed if and when the
exception handler is invoked
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
21
21
Catching and Handling Exceptions:
The finally block
• The finally block always (almost) executes when the try block exits.
• It avoids having cleanup code accidentally bypassed by a return,
continue, or break.
• Putting cleanup code in a finally block is always a good practice, even
when no exceptions are anticipated.
try {
} catch (ExceptionType name) {
} finally {
}
22
22
Specifying Exceptions Thrown by a Method
• To specify that a method can throw an exception, add a
throws clause to the method declaration.
• The throws clause comprises the throws keyword followed
by a comma-separated list of all the exceptions thrown by
that method.
• The clause goes after the method name and argument list
and before the brace that defines the scope of the
method.
public void myMethod() throws myException { … }
23
23
import java.util.Scanner;
import java.io.File;
import java.util.Scanner;
import java.io.File;
public class IOTester
{
public static void
main(String[] args) throws Exception
{
Scanner s = null;
s = new Scanner(new File("input.txt"));
s.useDelimiter(",");
while(s.hasNext())
{
String myString = s.next();
System.out.println(myString);
}
public class IOTester
{
public static void main(String[] args) {
Scanner s = null;
try {
s = new Scanner(new File("input.txt"));
s.useDelimiter(",");
}
catch(Exception e)
{
System.out.println("File issue");
}
while(s.hasNext())
{
String myString = s.next();
System.out.println(myString);
}
}
}
}
}
1
2
3
ObjectA
ObjectB
ObjectC
Exception
Exception
throws Exception
1
throws Exception
2
3
ObjectA
ObjectB
ObjectC
School
Tester
-school
1
main()
Student
-students
1
1
+School()
+loadStudents():void
+printRoster():void
*
-id: int
-name:String
+Student(int,String)
+toString():String
Data