CSS 161: Fundamentals of Computing

Slides:



Advertisements
Similar presentations
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.
Advertisements

Chapter 10 Ch 1 – Introduction to Computers and Java Streams and File IO 1.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
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.
Chapter 10 File I/O Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
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 
CS102--Object Oriented Programming Lecture 13: File I/O Copyright © 2008 Xiaoyan Li.
Files and Streams. Goals To be able to read and write text files To be able to read and write text files To become familiar with the concepts of text.
Files and Streams CS 21a Chapter 11 of Horstmann.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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 There’s more to life than the keyboard. Interactive vs. file I/O All of the programs we have seen or written thus far have assumed interaction.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Chapter 10 File I/O Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
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.
Chapter 10 Text Files Section 10.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
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 10 Introduction to File I/O Section 10.1 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Chapter 10 File I/O Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
© 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.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Up to slide 46 for 111. Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
CHAPTER 3 File Output.
Basic Text File Input/Output
File - CIS 1068 Program Design and Abstraction
Text File Input/Output
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Input/Output.
Reading from a file A file is typically stored on your computers hard drive. In the simplest case, lets just assume it is text. For a program to use.
Streams and File I/O.
Text File Input/Output
I/O Basics.
I/O Streams- Basics Byte Streams and Character Streams
Chapter 10 File I/O Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 10 File I/O Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CSS161: Fundamentals of Computing
Streams and File I/O Chapter 14.
Comp 249 Programming Methodology
File I/O ICS 111: Introduction to Computer Science I
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Computer Programming with JAVA
Chapter 10 File I/O Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage Copyright © 2016 Pearson Inc.
CMSC 202 Exceptions 2nd Lecture.
Classes, Objects and Methods
I/O Exceptions & Working with Files
CMSC 202 Exceptions 2nd Lecture.
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:

CSS 161: Fundamentals of Computing File Input & Output Joe McCarthy CSS 161: Fundamentals of Computing

CSS 161: Fundamentals of Computing Outline Streams Text files Output to text files Buffered output Exceptions Input from text files Portions of slides Copyright © 2012 Pearson Addison-Wesley. All rights reserved. CSS 161: Fundamentals of Computing

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 is called an input stream If the data flows out of a program, then the stream is called an output stream Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Streams Input streams can flow from the keyboard or a file System.in is an InputStream that connects to the keyboard, from which we can read bytes We typically use a Scanner object to access higher level objects via nextInt(), nextDouble() & nextLine(), etc., rather than reading 1 byte at a time Scanner keyboard = new Scanner(System.in); Output streams can flow to a screen or to a file System.out is a PrintStream that connects to the screen, to which we can write higher level objects System.out.println("Output stream");

CSS 161: Fundamentals of Computing Streams CSS 161: Fundamentals of Computing

CSS 161: Fundamentals of Computing Readers & Writers http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html CSS 161: Fundamentals of Computing

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 text files Text files are sometimes called ASCII files because the data they contain uses an ASCII encoding scheme American Standard Code for Information Interchange An advantage of text files is that the are usually the same on all computers, so that they can move from one computer to another Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

CSS 161: Fundamentals of Computing ASCII codes http://www.asciitable.com/ CSS 161: Fundamentals of Computing

Text Files and Binary Files Files that are designed to be read only by programs and that consist of a sequence of binary digits (bits) are called binary files Binary files are designed to be read on the same type of computer and with the same programming language as the computer that created the file An advantage of binary files is that they are more efficient to process than text files Unlike most binary files, Java binary files have the advantage of being platform independent Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Writing to a Text File The class PrintWriter is a stream class that can be used to write to a text file An object of the class PrintWriter has the methods print and println These are similar to the System.out methods of the same names, but are used for text file output, not screen output Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Writing to a Text File All the file I/O classes that follow are in the package java.io, so a program that uses PrintWriter will start with a set of import statements: import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException; The class PrintWriter has had no constructor that takes a file name as its argument (in earlier versions of Java) It uses another class, FileOutputStream, to convert a file name to an object that can be used as the argument to its (the PrintWriter) constructor Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

CSS 161: Fundamentals of Computing PrintWriter in Java 7 CSS 161: Fundamentals of Computing

Writing to a Text File A stream of the class PrintWriter is created and connected to a text file for writing as follows: PrintWriter writerName; writerName = new PrintWriter(new FileOutputStream(fileName)); The class FileOutputStream takes a string representing the file name as its argument The class PrintWriter takes the anonymous FileOutputStream object as its argument; could also use: FileOutputStream f = new FileOutputStream(fileName); writerName = new PrintWriter(f); Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Writing to a Text File This produces an object of the class PrintWriter that is connected to the file fileName The process of connecting a stream to a file is called opening the file If the file already exists, then doing this causes the old contents to be lost (or overwritten) If the file does not exist, then a new, empty file named fileName is created After doing this, the methods print and println can be used to write to the file Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

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 file could not be created This type of exception can also be thrown when a program attempts to open a file for reading and there is no such file It is therefore necessary to enclose this code in exception handling blocks The file should be opened inside a try block A catch block should catch and handle the possible exception The variable that refers to the PrintWriter object should be declared outside both blocks (and initialized to null) so that it is not local to the block Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Closing a Text File When a program is finished writing to a file, it should always close the stream connected to that file outputStreamName.close(); This allows the system to release any resources used to connect the stream to the file If the program does not close the file before the program ends, Java will close it automatically, but it is a good programming practice to close it explicitly Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Buffered Output Output streams connected to files are usually buffered Rather than physically writing to the file as soon as possible, the data is saved in a temporary memory location (buffer) The buffer is created and managed for you by Java; it can typically hold up to 512 bytes (= 256 characters) When the buffer becomes full, or when the method flush is explicitly invoked, the buffered data is written to the file all at once This is more efficient, since physical writes to a file on disk can be 1000+ times slower than writing to memory

Closing and Flushing The method close invokes the method flush, thus insuring that all the data is written to the file If a program relies on Java to close the file, and the program terminates abnormally, then any output that was buffered may not get written to the file Also, if a program writes to a file and later reopens it to read from the same file, it will have to be closed first; trying to open a file that is already open is an error The sooner a file is closed after writing to it, the less likely it is that there will be a problem So, always close a file as soon as you are done with it

PrintWriter with autoFlush This is inefficient and should generally be avoided. CSS 161: Fundamentals of Computing

File Names The rules for how file names should be formed depend on a given operating system, not Java When a file name is given to a java constructor for a stream, it is just a string, not a Java identifier (e.g., "filename.txt") The suffix used, such as .txt, has no special meaning to a Java program However, suffixes often have special meaning to the operating system (Windows, Mac OS, Linux)

A File Has Two Names Every input file and every output file used by a program has two names: The real file name used by the operating system (e.g., "output.txt") The name of the stream that is connected to the file (e.g., writer) The real file name is used to connect to the stream The stream name serves as an internal name for the file, and is primarily used within the program PrintWriter writer; writer = new PrintWriter(new FileOutputStream("output.txt"));

IOException When performing file I/O there are many situations in which an exception, such as FileNotFoundException, may be thrown Many of these exception classes are subclasses of the class IOException The class IOException is the root class for a variety of exception classes having to do with input and/or output These exception classes are all checked exceptions Therefore, they must be caught or declared in a throws clause Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Unchecked Exceptions In contrast, the exception classes NoSuchElementException, InputMismatchException, and IllegalStateException are all unchecked exceptions Unchecked exceptions are not required to be caught or declared in a throws clause Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Pitfall: a try Block is a Block Since opening a file can result in an exception, it should be placed inside a try block If the variable for a PrintWriter object needs to be used outside that block – which is nearly always the case – then the variable must be declared outside the block Otherwise it would be local to the block, and could not be used elsewhere If it were declared in the block and referenced elsewhere, the compiler will generate a message indicating that it is an undefined identifier

Appending to a Text File To create a PrintWriter object and connect it to a text file for appending, a second argument, set to true, must be used in the constructor for the FileOutputStream object writerName = new PrintWriter(new FileOutputStream(fileName, true)); After this statement, the methods print, println and/or printf can be used to write to the file The new text will be written after the old text in the file Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Some Methods of the Class PrintWriter (Part 1 of 3) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Some Methods of the Class PrintWriter (Part 2 of 3) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Some Methods of the Class PrintWriter (Part 3 of 3) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Reading From a Text File Using Scanner The class Scanner can be used for reading from the keyboard as well as reading from a text file Simply replace the argument System.in (to the Scanner constructor) with a suitable stream that is connected to the text file Scanner readerName = new Scanner(new FileInputStream(fileName)); Methods of the Scanner class for reading input behave the same whether reading from the keyboard or reading from a text file For example, the nextInt and nextLine methods Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Reading Input from a Text File Using Scanner (Part 1 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Reading Input from a Text File Using Scanner (Part 2 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Reading Input from a Text File Using Scanner (Part 3 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Reading Input from a Text File Using Scanner (Part 4 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Testing for the End of a Text File with Scanner A program that tries to read beyond the end of a file using methods of the Scanner class will cause an exception to be thrown However, instead of having to rely on an exception to signal the end of a file, the Scanner class provides methods such as hasNextInt and hasNextLine When reading from keyboard (System.in), hasNextLine will return false when user hits CTRL-D (holds down Control key and presses D key)

Checking for the End of a Text File with hasNextLine (Part 1 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Checking for the End of a Text File with hasNextLine (Part 2 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Checking for the End of a Text File with hasNextLine (Part 3 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Checking for the End of a Text File with hasNextLine (Part 4 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Checking for the End of a Text File with hasNextInt (Part 1 of 2) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Checking for the End of a Text File with hasNextInt (Part 2 of 2) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.