ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

Lecture 15: I/O and Parsing
Mr. Wortzman.  So far, we have gotten all our input and written all our output to the console  In reality, this is somewhat uncommon  Instead, we often.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
COMP 121 Week 5: Exceptions and Exception Handling.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Files from Ch4. 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.
James Tam Exception handling in Java Java Exception Handling Dealing with errors using Java’s exception handling mechanism.
CS 206 Introduction to Computer Science II 09 / 14 / 2009 Instructor: Michael Eckmann.
Nov 10, Fall 2006IAT 8001 Debugging. Nov 10, Fall 2006IAT 8002 How do I know my program is broken?  Compiler Errors –easy to fix!  Runtime Exceptions.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Files and Streams CS 21a Chapter 11 of Horstmann.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
CC1007NI: Further Programming Week 8-9 Dhruba Sen Module Leader (Islington College)
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Chapter 9-Text File I/O. Overview n Text File I/O and Streams n Writing to a file. n Reading from a file. n Parsing and tokenizing. n Random Access n.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
OO Design and Programming II I/O: Reading and Writing
Streams & File Input/Output (I/O)
Introduction Exception handling Exception Handles errors
Creating and Modifying Text part 2
Fall 2017 CISC124 9/21/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
Exceptions 10-Nov-18.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Streams and File I/O Chapter 14.
Unit 6 Working with files. Unit 6 Working with files.
Exception Handling.
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exceptions 10-May-19.
CMSC 202 Exceptions.
Presentation transcript:

ICS3U_FileIO.ppt File Input/Output (I/O)‏

ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name is "billy.txt”

ICS3U_FileIO.ppt File myFile = new File("billy.txt"); The data type of myFile is… … File What kind of data type is this? An abstract data type. (vs. concrete)‏

ICS3U_FileIO.ppt Create a New File createNewFile() method myFile.createNewFile(); // this creates // the file

ICS3U_FileIO.ppt When file creation goes horribly, horribly wrong If the file can’t be created an exception is thrown. IOException - means there was an I/O failure. It’s an unchecked exception Compiler: write some special code to handle the exception.

ICS3U_FileIO.ppt Exception Handlers try…catch block try { myFile.createNewFile(); System.out.println("file created"); } catch (java.io.IOException e) {//can call ‘e’ //anything System.out.println(”Oops!"); }

ICS3U_FileIO.ppt try…catch block try block: contains code you’re trying to execute and that might throw the exception. catch block: contains code that is executed when the exception is caught.

ICS3U_FileIO.ppt You Try Declare a file object Create the file Where do you suppose your program created the file? Use WinXp’s search function if you can’t locate the file yourself.

ICS3U_FileIO.ppt throws – the keyword Guess what? You don't absolutely need a try...catch block. You can use the throws keyword instead. It's simpler. But less elegant.

ICS3U_FileIO.ppt Using throw public static void main(String[] args) throws e.g. public static void main (String[] args) throws IOException, FileNotFoundException It’s simpler than try…catch but… Your program will crash when the exception occurs rather than do something elegant specified by the catch block.

ICS3U_FileIO.ppt Deleting Files We use the delete() method. E.g. myFile.delete(); The delete() method returns true if successful and false if not. Since we’re interacting with the OS, we should check for success. if(myFile.delete()) //OK. File was deleted. Continue processing. else System.out.println(“ERROR: File deletion failed.”);

ICS3U_FileIO.ppt Reading from a file We need a way to connect our program to the file we want to read. We use a stream.

ICS3U_FileIO.ppt Reading From A File: Creating a stream We need two things for a (useful) stream: a FileReader object and a BufferedReader object

ICS3U_FileIO.ppt Reading From A File: Creating a stream Create a FileReader object to use: FileReader myFileRdr = new FileReader(“billy.txt”); This presumes that “ billy.txt ” already exists. If not? An exception! FileNotFoundException (see slide 10)

ICS3U_FileIO.ppt Reading From A File: BufferedReader FileReader is good creating a stream to connect to a file but not much else. BufferedReader is good at reading from a stream. BufferedReader myBuffRdr = new BufferedReader (myFileRdr);

ICS3U_FileIO.ppt Reading From a File: BufferedReader BufferedReader needs to know what kind of streaming object it’s going to read from when it’s created. That’s why we pass the FileReader object ( myFileRdr ) to it when we create it. BufferedReader myBuffRdr = new BufferedReader (myFileRdr);

ICS3U_FileIO.ppt Reading from a File FileReader myFileRdr = new FileReader(“billy.txt); BufferedReader myBuffRdr = new BufferedReader(myFileRdr); myBuffRdr reads from the myFileRdr stream which is connected to billy.txt.

ICS3U_FileIO.ppt Using BufferedReader BufferedReader implements our old friend… … readLine() myBuffRdr.readLine() reads a line of text from the file that was pointed to by the FileReader object. i.e. we read a line from billy.txt

ICS3U_FileIO.ppt Using BufferedReader myBuffRdr.readLine() returns a string…(as usual) String fileLine; fileLine = myBuffRdr.readLine();

ICS3U_FileIO.ppt Reading until the End of the File (EOF) String fileLine; while ((fileLine = myBuffRdr.readLine()) != null) System.out.println(fileLine); At the end of the file ( EOF ), readLine() returns a special value called null instead of a string. Therefore, the loop runs, reading lines from the file, until readLine() returns null. null means we’re at the end of the file and should stop reading.

ICS3U_FileIO.ppt You try Follow the handout instructions to write a program called cat that puts all this together. ICS3U_catExercise.doc

ICS3U_FileIO.ppt Parsing/Splitting the Input String into words We need to be able to split the input line into individual words. We use the String method called split() to do this.

ICS3U_FileIO.ppt Parsing/Splitting the Input String into words String fileLine = myBuffRdr.readLine(); String[] words; words = fileLine.split(“ *“); We have two spaces followed by an asterisk here. This gives us an array of Strings. Each element of the array is one word from the line that we read from the file.

ICS3U_FileIO.ppt Parsing/Splitting the Input String into words split() uses the string inside the parentheses (i.e. the argument) to figure out how to divide up the string. If words[] was “this:is:an:unusual:line” and we wrote: words = fileLine.split(“:”); Then words[] would have “this” in element 0, “is” in element 1, “an” in element 2, “unusual” in element 3, etc. The argument to split is called a delimiter.

ICS3U_FileIO.ppt Parsing/Splitting the Input String into words The delimiter argument is a special type of expression called a regular expression. These are very useful tools for analyzing strings. But they can also be quite complicated. We use 2 spaces and an asterisk because that is a regular expression that means at least one but possibly many spaces. So if some words are separated by more than one space we’ll still break up the input into the words its composed of.

ICS3U_FileIO.ppt Print one word per line while((fileLine=myBuffRdr.readLine()) != null) { //assumes “:” is the field delimeter words = fileLine.split(“:”); for (int i = 0; i<words.length; i++) System.out.println(words[i]); }

ICS3U_FileIO.ppt You Do I’ve modified SamuraiSong.txt from yesterday and inserted colons between each word (using regular expressions, actually. Quite simple once you understand.) Open and read in SamuraiSong_Colonised.txt as you did in the cat exercise from yesterday. Split each input line up into a string array using a colon (“:”) as the delimeter. After reading each line from the file, print the string array word by word (I.e. each element) on a separate line.

ICS3U_FileIO.ppt

ICS3U_FileIO.ppt Writing Program Output to a File Very similar to reading from a file. Declare a FileWriter object which will connect to the file we want to write to. FileWriter myFileWrtr = new FileWriter("Billy.txt"); What do you suppose "Billy.txt" refers to?

ICS3U_FileIO.ppt Writing to a File Yup. It's the name of the file we want to write to. If the file doesn't exist, declaring the FileWriter object will create it. If the file does already exist, declaring the FileWriter object will overwrite it. You can also “append” to a file: FileWriter myFileWrtr = new FileWriter("Billy.txt“,true);

ICS3U_FileIO.ppt Writing to a File - BufferedWriter You also need a BufferedWriter (just like you needed a BufferedReader). BufferedWriter myBuffWrter = new BufferedWriter(myFWrtr);

ICS3U_FileIO.ppt Writing to a file - write() BufferedWriter has a write() method to use for writing a string to the file. myBuffWrtr.write("Billy is a bad boy."); myBuffWrtr.write("Bobby is too.");

ICS3U_FileIO.ppt Writing to a file - write() There’s a problem with the two previous lines of code. They produce outpout like this: Billy is a bad boy.Bobby is too. We need to use the newLine() method. myBuffWrtr.newLine();

ICS3U_FileIO.ppt Writing to a file - newLine () myBuffWrtr.write("Billy is a bad boy."); myBuffWrtr.newLine(); myBuffWrtr.write("Bobby is too."); Will produce: Billy is a bad boy. Bobby is too.

ICS3U_FileIO.ppt Writing to a file –format() Want more control over your output? Use the format() method in the String class – See pg 64 in your text

ICS3U_FileIO.ppt Writing to a file - close() When we’re done with the file we should tell the operating system to close it: myBuffWrtr.close();