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.

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
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.
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.
© 2000 Scott S Albert Structured Programming 256 Chapter 7 Streams and File I/O.
CS 206 Introduction to Computer Science II 09 / 14 / 2009 Instructor: Michael Eckmann.
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.
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 
HST 952 Computing for Biomedical Scientists Lecture 8.
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,
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Streams and File I/O Chapter 9. Objectives become familiar with the concept of an I/O stream understand the difference between binary files and text files.
Introduction To Scientific Programming Chapter 9 – Stream & File I/O.
CS0007: Introduction to Computer Programming File IO and Recursion.
Two Ways to Store Data in a File Text format Binary format.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
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.
Lecturer: Dr. AJ Bieszczad Chapter 9 COMP 150: Introduction to Object-Oriented Programming 9-1 l Overview of Streams and File I/O l Text File I/O l Binary.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 9 l Streams and Simple File I/O l Exception Handling with File.
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.
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.
1 CHAPTER 3 StringTokenizer. 2 StringTokenizer CLASS There are BufferedReader methods to read a line (i.e. a record) and a character, but not just a single.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
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.
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.
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.
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.
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.
1 Exceptions Exception handling – Exception Indication of problem during execution – E.g., divide by zero – Chained exceptions Uses of exception handling.
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.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
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.
GENERICS AND FILE HANDLING Saumya Srivastava (977934) Divyangana Pandey (977790) Shubhi Saxena (978108) Arka Das (962969) AHD05/15-16 AJA 21.
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.
CHAPTER 3 File Output.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
OO Design and Programming II I/O: Reading and Writing
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Streams and File I/O.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Streams and File I/O Chapter 9 Chapter 9.
Streams and File I/O Chapter 14.
CHAPTER 5 (PART 2) JAVA FILE INPUT/OUTPUT
CSS 161: Fundamentals of Computing
Computer Programming with JAVA
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
File Input and Output.
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:

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 a file Output can be to display (screen) or a file Advantages of file I/O –permanent copy –output from one program can be input to another –input can be automated (rather than entered manually)

Streams 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 a buffer between the data source and destination Input stream: a stream that provides input to a program –System.in is an input stream Output stream: a stream that accepts output from a program –System.out is an output stream A stream connects a program to an I/O object –System.out connects a program to the screen –System.in connects a program to the keyboard

Binary Versus Text Files All data and programs are ultimately just zeros and ones –each digit can have one of two values, hence binary –bit is one binary digit –byte is a group of eight bits Text files: the bits represent printable characters –one byte per character for ASCII, the most common code –for example, Java source files are text files –so is any file created with a "text editor" Binary files: the bits represent other types of encoded information, such as executable instructions or numeric data –these files are easily read by the computer but not humans –they are not "printable" files actually, you can print them, but they will be unintelligible "printable" means "easily readable by humans when printed"

Java: Text Versus Binary Files Text files are more readable by humans Binary files are more efficient –computers read and write binary files more easily than text Java binary files are portable –they can be used by Java on different machines –Reading and writing binary files is normally done by a program –text files are used only to communicate with humans Java Text Files Source files Occasionally input files Occasionally output files Java Binary Files Executable files (created by compiling source files) Usually input files Usually output files

Text Files vs. Binary Files Number: 127 (decimal) –Text file Three bytes: “1”, “2”, “7” ASCII (decimal): 49, 50, 55 ASCII (octal): 61, 62, 67 ASCII (binary): , , –Binary file: One byte ( byte ): Two bytes ( short ): Four bytes ( int ):

Text File I/O Important classes for text file output (to the file) –PrintWriter –BufferedWriter –FileWriter Important classes for text file input (from the file): –BufferedReader –FileReader FileWriter and FileReader take file names as arguments. PrintWriter and BufferedReader provide useful methods for easier writing and reading. Usually need a combination of the classes To use these classes your program needs a line like the following: import java.io.*;

Buffering Not buffered: each byte is read/written from/to disk as soon as possible –“little” delay for each byte –A disk operation per byte---higher overhead Buffered: reading/writing in “chunks” –Some delay for some bytes Assume 16-byte buffers Reading: access the first 4 bytes, need to wait for all 16 bytes are read from disk to memory Writing: save the first 4 bytes, need to wait for all 16 bytes before writing from memory to disk –A disk operation per a buffer of bytes---lower overhead

Text File Output To open a text file for output: connect a text file to a stream for writing fileout=new FileWriter(“smiley.txt"); BufferedWriter bufout=new BufferedWriter(fileout); PrintWriter out=new PrintWriter(bufout); Goal: create a PrintWriter object – which uses FileWriter to open a text file FileWriter“ connects” PrintWriter to a text file.

Output File Streams PrintWriter FileWriter Disk Memory out smiley.txt BufferedWriter fileout=new FileWriter(“out.txt"); BufferedWriter bufout=new BufferedWriter(fileout); PrintWriter out=new PrintWriter(bufout); bufoutfileout

Methods for PrintWriter Similar to methods for System.out println out.println(count + " " + line); print format flush : write buffered output to disk close : close the PrintWriter stream (and file)

12 Opening a File Opening a file for input will fail—causing an exception to be thrown—unless the file already exists. When an existing file is opened for output, the file is normally truncated—the bytes already in the file are lost. Attempting to open a nonexistent file for output will cause the file to be created. Either way, the file is empty to begin with.

Gotcha: Overwriting a File Opening an output file creates an empty file Opening an output file creates a new file if it does not already exist Opening an output file that already exists eliminates the old file and creates a new, empty one –data in the original file is lost To see how to check for existence of a file, see the section of the text that discusses the File class.

Java Tip: Appending to a Text File To add/append to a file instead of replacing it, use a different constructor for FileOutputStream or FileWriter : fileout=new FileWriter(“out.txt“, true); Second parameter: append to the end of the file if it exists? Sample code for letting user tell whether to replace or append:

15 Buffering and Flushing Java’s stream classes are designed to perform buffering without any action on the programmer’s part. Occasionally, though, it’s necessary to take a more active role. Normally, data written to a file goes into a buffer first. The buffer is flushed (written to the file) automatically when it’s full or the file is closed.

16 Buffering and Flushing The buffer can be flushed manually by calling the flush method: out.flush(); out can be an output stream or writer object Calling flush ensures that data is written to a file as soon as possible, where it will be safe. All output stream and writer classes support the flush method.

Closing a File An output file should be closed when you are done writing to it (and an input file should be closed when you are done reading from it). Use the close method of the class PrintWriter (BufferedReader also has a close method ). For example, to close the file opened in the previous example: outputStream.close(); If a program ends normally it will close any files that are open.

FAQ: Why Bother to Close a File? If a program automatically closes files when it ends normally, why close them with explicit calls to close ? Two reasons: 1. To make sure it is closed if a program ends abnormally (it could get damaged if it is left open). 2. A file opened for writing must be closed before it can be opened for reading. Although Java does have a class that opens a file for both reading and writing, it is not used in this text.

Text File Input To open a text file for input: connect a text file to a stream for reading –Goal: a BufferedReader object, which uses FileReader to open a text file –FileReader “ connects” BufferedReader to the text file For example: BufferedReader smileyInStream = new BufferedReader(new FileReader(“smiley.txt")); Similarly, the long way : FileReader s = new FileReader(“smiley.txt"); BufferedReader smileyInStream = new BufferedReader(s);

fileread = new FileReader (“in.txt"); BufferedReader in = new BufferedReader(fileread); String line = in.readLine(); while (line != null) { line = in.readLine(); System.out.println(line); } in.close();

Input File Streams BufferedReader FileReader Disk Memory smileyInStream smiley.txt BufferedReader smileyInStream = new BufferedReader( new FileReader(“smiley.txt”) );

Methods for BufferedReader readLine : read a line into a String no methods to read numbers directly, so read numbers as String s and then convert them ( StringTokenizer ) read : read a char at a time close : close BufferedReader stream

23 Exceptions in Handling with File I/O Checked exceptions that can occur: –The FileInputStream constructor can throw FileNotFoundException. –The FileOutputStream constructor can throw IOException (or FileNotFoundException ). –The read method in FileInputStream can throw IOException. –The write method in FileOutputStream can throw IOException. –The close methods in FileInputStream and FileOutputStream can throw IOException.

Exception Handling with File I/O Catching IOExceptions IOException is a predefined class File I/O might throw an IOException catch the exception in a catch block that at least prints an error message and ends the program FileNotFoundException is derived from IOException –therefor any catch block that catches IOException s also catches FileNotFoundException s –put the more specific one first (the derived one) so it catches specifically file-not-found exceptions –then you will know that an I/O error is something other than file- not-found

25 Exceptions in the Program Instead of having a separate try block and catch block for each exception, most of the program will be enclosed within a single try block. After the try block will come two catch blocks, one for FileNotFoundException and one for IOException.

Reading Words in a String: Using StringTokenizer Class There are BufferedReader methods to read a line and a character, but not just a single word StringTokenizer can be used to parse a line into words –import java.util.* –some of its useful methods are shown in the text e.g. test if there are more tokens –you can specify delimiters (the character or characters that separate words) the default delimiters are "white space" (space, tab, and newline)

Example: StringTokenizer Display the words separated by any of the following characters: space, new line (\n), period (.) or comma (,). String inputLine = in.readLine(); StringTokenizer wordFinder = new StringTokenizer(inputLine); while(wordFinder.hasMoreTokens()) { System.out.println(wordFinder.nextToken()); } Question 2b or !tooBee Entering " Question,2b.or !tooBee. " gives this output:

Testing for End of File in a Text File When readLine tries to read beyond the end of a text file it returns the special value null –so you can test for null to stop processing a text file read returns -1 when it tries to read beyond the end of a text file –the int value of all ordinary characters is nonnegative Neither of these two methods ( read and readLine ) will throw an EOFException.

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 29 Excerpt from TextEOFDemo Example: Using Null to Test for End-of-File in a Text File When using readLine test for null When using read test for -1