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.

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

Lecture 15: I/O and Parsing
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Today Quiz solutions are posted on the Grading page. Assignment 2 is posted. Due the first Friday after Reading Week. All about null Start File Input/Output.
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
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.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
CS 206 Introduction to Computer Science II 09 / 09 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
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.
CS 206 Introduction to Computer Science II 09 / 04 / 2008 Instructor: Michael Eckmann.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
CS 206 Introduction to Computer Science II 01 / 23 / 2009 Instructor: Michael Eckmann.
Io package as Java’s basic I/O system continue’d.
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.
CSC – Java Programming II Lecture 9 January 30, 2002.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
1 Course Lectures Available on line:
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
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.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Chapter 10 Text Files Section 10.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
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.
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.
Java Input and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
© 2004 Pearson Addison-Wesley. All rights reserved December 5, 2007 I/O Exceptions & Working with Files ComS 207: Programming I (in Java) Iowa State University,
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.
Introduction to Exceptions in Java CS201, SW Development Methods.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
OO Design and Programming II I/O: Reading and Writing
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Introduction to Computer Science / Procedural – 67130
Streams and File I/O.
Program Input/Output (I/O)
I/O Basics.
Creating and Modifying Text part 2
Streams and File I/O Chapter 14.
CSS 161: Fundamentals of Computing
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
I/O Exceptions & Working with Files
Exceptions 10-May-19.
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

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

Fall 2002CS 150: Intro. to Computing2 Streams Abstractly, a stream is a flow of data –Data could be characters, numbers, bytes consisting of binary digits, bytes consisting of binary encoding of objects, etc. If the data flows “out” of your program (and, say, to a file or the monitor) then the stream is an output stream If the data flows “in” to your program, then the stream is an input stream

Fall 2002CS 150: Intro. to Computing3 Streams In Java, file I/O (and also simple keyboard/monitor I/O) is handled by streams –In Java, a stream is an object that either delivers data to its destination (such as a file or monitor) or takes data from a source (such as a file or keyboard) and delivers it to your program –System.out is an example of an output stream

Fall 2002CS 150: Intro. to Computing4 Streams Program File, Monitor, Network, Etc. File, Keyboard, Network, Etc. output stream input stream

Fall 2002CS 150: Intro. to Computing5 Remember: An input stream moves data into your program (not into a file) An output stream moves data out of your program (not out of the file)

Fall 2002CS 150: Intro. to Computing6 Binary vs Text Files All data in any file is stored as a sequence of bits. But, sometimes we “think” of the file as consisting of a sequence of characters (for example, your Java source code files), and some we think of as simply containing a sequence of binary digits (such as a file containing the machine code for a program) The files of characters are called text files The files of bits are called binary files Java has objects to handle I/O to both kinds of files. We’ll only work with text files

Fall 2002CS 150: Intro. to Computing7 Text File I/O Best to just start with an example: we’ll add some file I/O to StudentRecord Must be here!

Fall 2002CS 150: Intro. to Computing8 Text File I/O (cont.) We use the println() method in the class PrintWriter (not System.out.println(), but acts the same) Returns a reference to an OutputStream object

Fall 2002CS 150: Intro. to Computing9

Fall 2002CS 150: Intro. to Computing10

Fall 2002CS 150: Intro. to Computing11 What’s with these?!

Fall 2002CS 150: Intro. to Computing12 Another Look…

Fall 2002CS 150: Intro. to Computing13 What’s With This try … catch Thing?! This is an example of exception handling in Java (which we may cover more completely at a later date) For now, know that this says: execute the statements in the try block. If something goes wrong, then stop and execute the statements in the catch block –Lots can go wrong with file I/O (e.g. the file may not exist, or you may not have permission to access it)

Fall 2002CS 150: Intro. to Computing14 Subtle and Very Important… If written this way, the variable outputStream is local to the try block!

Fall 2002CS 150: Intro. to Computing15 Still Another Look… Here it’s visible throughout the whole method What’s with this?!

Fall 2002CS 150: Intro. to Computing16 So, How Do We Use These Things?! Just like you use System.out.println(), though there are also methods specially designed to print doubles, chars, etc.

Fall 2002CS 150: Intro. to Computing17 Writing To a File (cont.) This is a variable name! I could have called it any legal variable name.

Fall 2002CS 150: Intro. to Computing18 Writing To a File (cont.) Why don’t I need to use getName() here?

Fall 2002CS 150: Intro. to Computing19 Still More Writing To a File

Fall 2002CS 150: Intro. to Computing20

Fall 2002CS 150: Intro. to Computing21 close() the Stream! Calling the close() method: –Flushes the stream –Operating system releases all resources needed to connect the stream to the file, and performs other housekeeping –If stream isn’t closed, Java closes it when the program ends, but you’re taking a chance… If program ends abnormally, then Java may not be able to automatically close the stream and you could lose data You need to close a stream before reading from the same file

Fall 2002CS 150: Intro. to Computing22 A True Story…

Fall 2002CS 150: Intro. to Computing23 Why Ever flush() a Stream? There are situations where you want the stream to remain open (you’re still using it), but you need to be sure data goes to output device Writing to a network interface During long operations on a file, flush stream in case there is some kind of abnormality –OS crash, etc.

Fall 2002CS 150: Intro. to Computing24 Miscellaneous File names: The file name you give Java is simply a String. It doesn’t know about suffixes and the like. That’s the OS’s thing. Opening a text file for appending: Indicates open for appending

Fall 2002CS 150: Intro. to Computing25 Streams and File I/O Part II Reading from Files

Fall 2002CS 150: Intro. to Computing26 BufferedReader Class The BufferedReader class is the input stream equivalent of the PrintWriter class –The constructor requires a similar setup –The class methods are analogous –Remember to import java.io.* –Remember this is for reading text files

Fall 2002CS 150: Intro. to Computing27

Fall 2002CS 150: Intro. to Computing28 The FileReader class is a subclass of the Reader class, so using it in the constructor is “legal”

Fall 2002CS 150: Intro. to Computing29

Fall 2002CS 150: Intro. to Computing30 What’s with this override thing? Note the exceptions that can be thrown

Fall 2002CS 150: Intro. to Computing31 Reading From Files As with writing to files, you need to know “where” you are in the file when reading Unlike with writing, you need to know when you have run out of stuff to read in the file When reading, you generally need to have a place (i.e. a variable) to put the data you have read Beware: there are many subtleties here

Fall 2002CS 150: Intro. to Computing32 Anything look strange here? It should!

Fall 2002CS 150: Intro. to Computing33

Fall 2002CS 150: Intro. to Computing34 Example Some new file-reading code added to the code that created the file profsGrades.txt

Fall 2002CS 150: Intro. to Computing35 Example (cont.) Adding a simple cast to a char will fix this problem, but there are others (see next slide)

Fall 2002CS 150: Intro. to Computing36

Fall 2002CS 150: Intro. to Computing37 Note the Changes… The entirety of the input code is in the try block (including closing the stream), not just the memory allocation for the stream There are two different classes of exceptions that are caught here: FileNotFoundException and IOException This is how you should write your I/O code!

Fall 2002CS 150: Intro. to Computing38 Running the Example Code

Fall 2002CS 150: Intro. to Computing39 Augmenting Our Code What the read documentation didn’t tell you is that the read() method returns the integer value  1 if there is no more file to read We’ll use this to modify our code to read (and print to standard output) the entire file

Fall 2002CS 150: Intro. to Computing40 NOTE! (see next slide)

Fall 2002CS 150: Intro. to Computing41 Notes From Last Slide myChar is declared an int, since we’ll need to check an integer value to see if we’re at the end of the file We use an infinite loop to keep iterating until we’ve read the entire file We call the read() method within the conditional for the if statement. Regardless of whether the condition is true, the call to read() occurs (this is a standard hack for this kind of code)

Fall 2002CS 150: Intro. to Computing42 More Notes… We use the print() method as opposed to the println() method – when a newline character is encountered, this will cause a new line in the output We perform the cast to char inside the System.out.print () statement

Fall 2002CS 150: Intro. to Computing43 There Are Easier Ways Use another version of the read() method to read characters into a char array Use the readline() method, which reads a whole line at a time into a String

Fall 2002CS 150: Intro. to Computing44

Fall 2002CS 150: Intro. to Computing45 More read() Documentation

Fall 2002CS 150: Intro. to Computing46 Often the Best Way…

Fall 2002CS 150: Intro. to Computing47 A problem

Fall 2002CS 150: Intro. to Computing48 The Problem The readLine() method returns the value null if it reaches the end of file. When this happens, the variable currentLine is assigned the value null, which causes a NullPointerException when we try to call its equals() method in the if statement. See the fix on either of the next two slides (the first is the recommended fix)

Fall 2002CS 150: Intro. to Computing49 A fix

Fall 2002CS 150: Intro. to Computing50 Another fix

Fall 2002CS 150: Intro. to Computing51 Reading Numeric Data Types Note that using any of the BufferedReader methods results in reading either a String or a char. To read a double or int or other numerical data type, you need to –Use methods like stringToInt() –Use methods like Double.parseDouble(String input) The method Integer.parseInt(String input) is the exact equivalent of stringToInt()

Fall 2002CS 150: Intro. to Computing52 Finally, Reading Input From the Keyboard The keyboard is an input device like any other, and we can read it with an input stream We use the read() m ethod in System.in –This works like our other read() method, but reads from the keyboard We use the above read() method to create a static readLine() method that we can call to read from the keyboard

Fall 2002CS 150: Intro. to Computing53

Fall 2002CS 150: Intro. to Computing54 This is needed in order to handle both Unix and Windows style end of line conventions

Fall 2002CS 150: Intro. to Computing55 A Tester For KeyboardIn Don’t forget that we need to use a try block with this