Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.

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
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
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.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
Lecture 31 File I/O -Part 2 COMP1681 / SE15 Introduction to Programming.
Chapter 9 Streams and File I/O Overview of Streams and File I/O
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
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.
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
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.
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.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with.
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.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Working with files By the end of this lecture you should be able to: explain the principles of input and output and identify a number of different input.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
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.
Java I/O Writing and Reading Objects to File Serialization.
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
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.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
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.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
Chapter 9 1 Chapter 9 – Part 2 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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Files and Serialization. Files Used to transfer data to and from secondary storage.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
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.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
Java IO Exploring the java.io package and living to talk about it.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
OO Design and Programming II I/O: Reading and Writing
Streams and File I/O.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
Accessing Files in Java
Programming in Java Files and I/O Streams
Streams and File I/O Chapter 9 Chapter 9.
Streams and File I/O Chapter 14.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Presentation transcript:

Chapter 91 Streams and File I/O Chapter 9

2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105 –Chapters 5–9 Discussion group after Spring Break –Monday, B155, 7:00 – 9:00pm –Exam review!

3 File I/O Why bother? Persistent storage  Use over multiple sessions  Safety In case of failure (program, computer) What are files? Collections of bytes  Can be abstracted and viewed otherwise Different Types?

4 Streams All file I/O is treated like a stream  Moving flow of data Different classes can work with the stream –Provide filters and abstractions –Like an assembly line for data File FileInputStrea m Lots of data DataInputStream bytes int char boolean double String

5 Streams A stream can only flow in one direction.  Need input streams and output streams Useful classes: General File String (split) JFileChooser Input FileInputStream DataInputStream ObjectInputStream FileReader BufferedReader Scanner Output FileOutputStream DataOutputStream ObjectOutputStream (FileWriter) PrintWriter

Chapter 96 Text Files and Binary Files All data in a file is stored as binary digits. –Files with contents that must be treated as sequences of binary digits are called binary files; binary files can be read only by machines.

Chapter 97 Text Files and Binary Files, cont. Sometimes, it is more convenient to think of a file’s contents as a sequence of characters. –Files with streams and methods to make them look like sequences of characters are called text files; text files can be read by people.

Chapter 98 Text Files and Binary Files, cont. However, binary files are more efficient to process than text files. In Java, binary files are platform- independent. –Binary files can be created by one computer and read by another, combining portability and efficiency.

Chapter 99 Text Files and Binary Files, cont. Though text files can be read and written using an editor, binary files must be read and written by a program.

10 Example 1 What does the following program do? try { String in = "in.txt"; int numLines = 5; BufferedReader reader = new BufferedReader( new FileReader( in ) ); for ( int line = 0; line < numLines; ++line ) { System.out.println( reader.readLine() ); } } catch( IOException ioe ) { System.err.println( "Crush! Kill! Destroy!" ); } What if the number of lines is unknown? Is there anything missing?

11 Example 2 try { String in = "in.txt"; BufferedReader reader = new BufferedReader( new FileReader( in ) ); String line = reader.readLine(); while( null != line ) { System.out.println( reader.readLine() ); line = reader.readLine(); } } catch( IOException ioe ) { System.err.println( "I can't do that, Dave!" ); } But we still need to close it! Where? What changes when reading a byte at a time?

12 Example 3 BufferedReader reader = null; try {... } catch( IOException ioe ){... } finally { try { if ( null != reader ) reader.close(); } catch( IOException ioe ) { System.err.println( "Error closing file" ); } close() should almost always be called in a finally block! close() should almost always be called in a finally block!

13 Scanner Class import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException;... try { Scanner scanner = new Scanner( new File( “in.txt” ) ); while( scanner.hasNextLine() ) { System.out.println( scanner.nextLine() ); } } catch( FileNotFoundException e ) { System.err.println( "Unable to open file!" ); }

Chapter 914 Use toString for Text-File Output Classes typically include a method toString. The methods println and print in class PrintWriter behave like System.out.println and System.out.print, respectively.

15 Example - toString() PrintWriter writer = null; try { String outFile = "out.txt"; writer = new PrintWriter(new FileOutputStream(outFile)); Date today = new Date(); writer.println( today.toString() ); writer.println( "Today is " + today ); } catch( FileNotFoundException ioe ) { System.err.println( "Exterrrrrrminate!" ); } finally {...} Notice: toString() is part of any object

Chapter 916 StringTokenizer Class Class BufferedReader can read entire lines or single characters, but not single words. Class StringTokenizer can take an entire line of text and break it into individual words. The class StringTokenizer is in the java.util package. Individual words are called tokens.

Chapter 917 StringTokenizer example Tokens are nonwhitespace characters. StringTokenizer tokenizer = new StringTokenizer(“Read my lips!”) while (tokenizer.hasMoreTokens()) { System.out.println( tokenizer.nextToken() ); } produces Read my lips!

Chapter 918 StringTokenizer, cont'd Separators are whitespace characters unless otherwise specified. To specify a set of separators, a string consisting of all the separator characters is given as a second argument to the constructor. example … new StringTokenizer(“Read my lips!”, “\n.,!”);

Chapter 919 String.split() example StringTokenizer is a legacy class! – use String split() method String s = “Read my lips!” String[] tokens = s.split( “ “ ); for( String token : tokens ) { System.out.println( token ); } produces Read my lips! split() argument is the delimeter

Chapter 920 Using the File Class The methods of the class File can check the properties of files. –Does the named file exist? –Is the file readable? Typically, the operating systems lets you designate files as not readable or as readable only by certain users.

Chapter 921 Using the File Class, cont. The File class is like a wrapper class for strings which are file names. –example new File(“treasure.txt”)

Chapter 922 Some File Methods public boolean exists() public boolean canRead() public boolean canWrite() public boolean delete() public boolean length() public String getName() public String getPath() Can these be used to avoid exceptions?

23 Object I/O Object I/O can be binary ObjectInputStream and ObjectOutputStream ObjectOutputStream oos = new ObjectOutputStream new FileOutputStream( ) ); oos.writeObject( new Date() );... ObjectInputStream ois = new ObjectInputStream new FileInputStream( ) ); Date aDate = (Date)ois.readObject();

Chapter 924 Output to Binary Files Using ObjectOutputStream class BinaryOutputDemo

Chapter 925 The EOFException Class ObjectInputStream methods that read from a binary file throw an EOFException when they try to read beyond the end of the file. When using class ObjectInputStream, the class EOFException can test for the end of a file.

Chapter 926 EOFException Example Does the order you catch Exceptions matter?

Chapter 927 Checking for the End of File Different classes with file reading methods check for the end of a file in different ways. –Binary files throw an exception in the class EOFException. –A text file returns a special value, such as null. Be sure to test for the end of the file in the correct way.

28 Object Stream Concerns Could an instance of the following class be written: public class SomeClass { String aString = “someText”; } Why or why not?

29 Object Stream Concerns Any object serialized by a stream must implement Serializable - Acts as a marker for what can be written public class SomeClass implements Serializable { String aString = “someText”; }

Chapter 930 The Serializable Interface A class which is serializable affects how Java performs file I/O with objects of the class. –Java assigns a serial number to each object of the class that it writes to a stream of type ObjectOutputStream. –If the object is written more than once, Java writes only the serial number for the object.

Chapter 931 Array Objects in Binary Files An entire array can be saved to a binary file using objectWrite, and can be read later using objectRead. If the base type of the array is a class, the class should be serializable. All the data in an array can be outputted to a binary file using a single invocation of objectWrite.

Chapter 932 (optional) Graphics Supplement Programming Example: A JFrame GUI for Manipulating Files –Accept a file and display its first line. –Provide an explanatory message if the file does not exist or is unreadable. –Delete a selected file. –Provide an explanatory message if the file does not exist or is unwriteable (and hence cannot be deleted).

Chapter 933 Graphics Supplement class FileOrganizer

Chapter 934 Graphics Supplement, cont. class FileOrganizer, cont.

Chapter 935 Graphics Supplement, cont. class FileOrganizer, cont.

Chapter 936 Graphics Supplement, cont.