Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 1341 File I/O Exception Handling. Introduction to File Processing Data stored in variables and arrays is temporary. Main Memory Main Memory Secondary.

Similar presentations


Presentation on theme: "CSE 1341 File I/O Exception Handling. Introduction to File Processing Data stored in variables and arrays is temporary. Main Memory Main Memory Secondary."— Presentation transcript:

1 CSE 1341 File I/O Exception Handling

2 Introduction to File Processing Data stored in variables and arrays is temporary. Main Memory Main Memory Secondary Memory Secondary Memory CPU Control Unit Control Unit ALU Registers Output Devices Output Devices Input Devices Input Devices

3 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. Main Memory Main Memory Secondary Memory Secondary Memory CPU Control Unit Control Unit ALU Registers Output Devices Output Devices Input Devices Input Devices

4 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.

5 meroL Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Java Program Java Program End-of-file marker

6 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.

7

8

9

10

11 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.

12 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.

13

14

15 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..

16 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. Exception Handling

17 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 ExceptionError CheckedUnchecked

18 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 { } public void myMethod() throws myException { … } And/Or

19 Catching and Handling Exceptions Three exception handler components try { } catch (ExceptionType name) { } finally { }

20 20 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 { }

21 21 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) { }

22 22 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 { }

23 23 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 { … }

24 import java.util.Scanner; import java.io.File; 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); } 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); }

25 1 1 2 2 3 3 ObjectA ObjectBObjectC

26 1 1 2 2 3 3 ObjectA ObjectBObjectC throws Exception Exception throws Exception Exception

27 Student -id: int -name:String -id: int -name:String +Student(int,String) +toString():String +Student(int,String) +toString():String School +School() +loadStudents():void +printRoster():void +School() +loadStudents():void +printRoster():void * 1 Tester main() 11 -students-school

28

29 Data Method


Download ppt "CSE 1341 File I/O Exception Handling. Introduction to File Processing Data stored in variables and arrays is temporary. Main Memory Main Memory Secondary."

Similar presentations


Ads by Google