Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)

Slides:



Advertisements
Similar presentations
Lecture 15: I/O and Parsing
Advertisements

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.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
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.
© 2000 Scott S Albert Structured Programming 256 Chapter 7 Streams and File I/O.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
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
Chapter 10 File I/O Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
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.
Unit 211 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files.
HST 952 Computing for Biomedical Scientists Lecture 8.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Unit 201 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from 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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
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 9. Objectives become familiar with the concept of an I/O stream understand the difference between binary files and text files.
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.
Introduction To Scientific Programming Chapter 9 – Stream & File I/O.
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.
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.
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.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Streams and File I/O.
1 StringTokenization Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples.
Two Ways to Store Data in a File  Text format  Binary format.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
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.
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.
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.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 10 File I/O Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
GENERICS AND FILE HANDLING Saumya Srivastava (977934) Divyangana Pandey (977790) Shubhi Saxena (978108) Arka Das (962969) AHD05/15-16 AJA 21.
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.
Up to slide 46 for 111. Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
CMSC 202 Text File I/O.
Streams and File I/O.
Streams and File I/O.
I/O Basics.
CSS161: Fundamentals of Computing
Streams and File I/O Chapter 9 Chapter 9.
Streams and File I/O Chapter 14.
Computer Programming with JAVA
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
FINAL EXAM Final Exam Tuesday, May 3: 1:00 - 3:00 PM (Phys 112)
Presentation transcript:

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks) l Spring Break next week – NO CLASS l Exam 2 »Thursday, March 24, 8:30-9:30pm »FRNY G140 »Chapters 5-9 »Same format as before (MC + programming)

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Binary Versus Text Files l All data and programs are ultimately just zeros and ones »each digit can have one of two values, hence binary »However when we say “binary files” we do not mean all files... l 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 l Binary files: the bits represent 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"

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 3 Text File Output l To open a text file for output: connect a text file to a stream for writing »create a stream of the class PrintWriter and connect it to a text file For example: PrintWriter outputStream = new PrintWriter(new FileOutputStream("out.txt")); Then you can use print and println to write to the file outputStream.println(count + " " + line); The text lists some other useful PrintWriter methods

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 4 Text File Input l To open a text file for input: connect a text file to a stream for reading »use a stream of the class BufferedReader and connect it to a text file »use the FileReader class to connect the BufferedReader object to the text file l For example: BufferedReader inputStream = new BufferedReader(new FileReader("data.txt")); Then: »read lines ( Strings ) with readLine »BufferedReader has no methods to read numbers directly, so read numbers as String s and then convert them »read a char with read

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 5 Every File Has Two Names l The code to open the file creates two names for an output file »the name used by the operating system –out.txt in the example »the stream name –outputStream in the example l Java programs use the stream name »outputStream in the example

Example: Reading a File Name from the Keyboard Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 6 TextFileInputDemo2 reading a file name from the keyboard closing the file using the file name read from the keyboard reading data from the file

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 7 Text File I/O Example public static void main (String [] args) { PrintWriter outputStream = null; try { outputStream = new PrintWriter(FileOutputStream(“out.txt”)); } catch (FileNotFoundException e) { System.out.println (“out.txt not found.”); System.exit(0); }

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 8 Text File I/O Example Continued // Suppose we have a method called results() // that returns a String, and we want to save // the results of three calls to this method // to our file. for (int i = 0; i < 3; i++) { outputStream.println(results()); // Print hyphens to separate results outputStream.println(“---”); } outputStream.close(); }

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Text File I/O Example Continued // In another program, read and print the results // in out.txt but do not print the lines of hyphens public static void main (String [] args) { BufferedReader inputStream = null; try { inputStream = new BufferedReader (new FileReader(“out.txt”)); String line = “”; while (line != null) { line = inputStream.readLine(); System.out.println(inputStream.readLine()); inputStream.readLine(); // Throw away “---” // This assumes each results line is followed by // “---”, not always a safe assumption! } // end while } // end try

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 10 Text File I/O Example Continued catch (FileNotFoundException e) { System.out.println (“out.txt not found”); } catch (EOFFileException e) { System.out.println (“End of file found before expected.”); } catch (IOException e) { System.out.println (“Error reading file.”); } finally { inputStream.close(); }

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 11 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 »it is in the util library so you need to 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)

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 12 StringTokenizer Methods l hasMoreTokens() »Returns true of the StringTokenizer object has additional tokens. This method does not remove the tokens. l nextToken() »This method returns the next token and removes it from the string tokenizer. l countTokens() »Returns the number of tokens remaining in the string tokenizer. (I.e. the number of remaining tokens to returned by nextToken.)

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 13 Example: StringTokenizer l Display the words separated by any of the following characters: space, new line (\n), period (.) or comma (,). String inputLine = SavitchIn.readLine(); StringTokenizer wordFinder = new StringTokenizer(inputLine, " \n.,"); //the second argument is a string of the 4 delimiters while(wordFinder.hasMoreTokens()) { System.out.println(wordFinder.nextToken()); } Question 2b or !tooBee Entering " Question,2b.or !tooBee. " gives this output:

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 14 StringTokenizer example: program public static final int MAX_NUMBERS = 100;... String[] numberList = new String [MAX_NUMBERS]; System.out.println(“To: “); String inputLine = SavitchIn.readLine(); // User can separate addresses by commas or spaces StringTokenizer numberFinder = new StringTokenizer(inputLine, “, ”); int count = 0; while (numberFinder.hasMoreTokens() && (count < MAX_NUMBERS)) { toAddresses[count] = numberFinder.nextToken(); }

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 15 Review: What is Binary I/O? l Allows us to write any data type (int, double, etc.) instead of just Strings as in text file I/O. (We will discuss writing objects soon.) l Classes for binary output: »ObjectOutputStream, FileOutputStream l Classes for binary input: »ObjectInputStream, FileInputStream l Some methods to write data to the file: »writeInt(int n), writeBoolean(boolean b), writeChar(char c), etc. l Some methods to read data from the file: »readInt(), readDouble(), readBoolean(), etc. l These methods can throw an IOException but.....

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 16 Opening a New Output File The file name is given as a String »file name rules are determined by your operating system l Opening an output file takes two steps 1. Create a FileOutputStream object associated with the file name String 2.Connect the FileOutputStream to an ObjectOutputStream object This can be done in one line of code

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 17 Example: Opening an Output File To open a file named numbers.dat : ObjectOutputStream outputStream = new ObjectOutputStream( new FileOutputStream("numbers.dat")); The constructor for ObjectOutputStream requires a FileOutputStream argument The constructor for FileOutputStream requires a String argument »the String argument is the output file name l The following two statements are equivalent to the single statement above: FileOutputStream middleman = new FileOutputStream("numbers.dat"); ObjectOutputStream outputStream = new ObjectOutputSteam(middleman);

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 18 Some ObjectOutputStream Methods l You can write data to an output file after it is connected to a stream class »Use methods defined in ObjectOutputStream –writeInt(int n) –writeDouble(double x) –writeBoolean(boolean b) –etc. –See the text for more Note that each write method might throw an IOException »eventually we will have to write a catch block for it Also note that each write method includes the modifier final »final methods cannot be redefined in derived classes

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 19 When Using ObjectInputStream to Read Data from Files: Input files are binary and contain any of the primitive data types ( int, char, double, etc.) and the String type l The files can be read by Java programs but are not printable The Java I/O library must be imported including the line: import java.io.*; »it contains ObjectInputStream and other useful class definitions An IOException might be thrown

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 20 Opening a New Input File l Similar to opening an output file, but replace "output" with "input" The file name is given as a String »file name rules are determined by your operating system l Opening a file takes two steps 1. Creating a FileInputStream object associated with the file name String 2. Connecting the FileInputStream to an ObjectInputStream object l This can be done in one line of code

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 21 Example: Opening an Input File To open a file named numbers.dat : ObjectInputStream inStream = new ObjectInputStream (new FileInputStream("numbers.dat")); The constructor for ObjectInputStream requires a FileInputStream argument The constructor for FileInputStream requires a String argument »the String argument is the input file name l The following two statements are equivalent to the statement at the top of this slide: FileInputStream middleman = new FileInputStream("numbers.dat"); ObjectInputStream inputStream = new ObjectInputStream (middleman);

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 22 Some ObjectInputStream Methods l For every output file method there is a corresponding input file method l You can read data from an input file after it is connected to a stream class »Use methods defined in ObjectInputStream –readInt() –readDouble() –readBoolean() –etc. –See the text for more Note that each read method might throw an IOException Also note that each read method includes the modifier final

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 23 Input File Exceptions A FileNotFoundException is thrown if the file is not found when an attempt is made to open a file Each read method might throw an IOException »we still have to write a catch block for it If a read goes beyond the end of the file an EOFException is thrown

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 24 Avoiding Common ObjectInputStream File Errors There is no error message (or exception) if you read the wrong data type! l Input files can contain a mix of data types »it is up to the programmer to know their order and use the correct read method ObjectInputStream works with binary, not text files l As with an output file, close the input file when you are done with it

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 25 Common Methods to Test for the End of an Input File l A common programming situation is to read data from an input file but not know how much data the file contains l In these situations you need to check for the end of the file l There are three common ways to test for the end of a file: 1. Put a sentinel value at the end of the file and test for it. 2. Throw and catch an end-of-file exception. 3. Test for a special character that signals the end of the file (text files often have such a character).

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 26 The EOFException Class Many (but not all) methods that read from a file throw an end-of-file exception ( EOFException ) when they try to read beyond the file »all the ObjectInputStream methods in Display 9.3 do throw it The end-of-file exception can be used in an "infinite" ( while(true) ) loop that reads and processes data from the file »the loop terminates when an EOFException is thrown The program is written to continue normally after the EOFException has been caught

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 27 Using EOFException Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 27 main method from EOFExceptionDemo Intentional "infinite" loop to process data from input file Note order of catch blocks: the most specific is first and the most general last Loop exits when end-of- file exception is thrown Processing continues after EOFException : the input file is closed

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 28 Binary I/O of Class Objects l read and write class objects in binary file l class must be serializable »import java.io.* »implement Serializable interface »add implements Serializable to heading of class definition l methods used: to write object to file: writeObject method in ObjectOutputStream to read object from file: readObject method in ObjectInputStream public class Species implements Serializable

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 29 outputStream = new ObjectOutputStream( new FileOutputStream("species.records"));... Species oneRecord = new Species("California Condor", 27, 0.02);... outputStream.writeObject(oneRecord); inputStream = new ObjectInputStream( new FileInputStream("species.records"));... Species readOne = null;... readOne = (Species)inputStream.readObject(); readObject returns a reference to type Object so it must be cast to Species before assigning to readOne ClassIODemo Excerpts

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 30 The File Class l Acts like a wrapper class for file names A file name like " numbers.dat " has only String properties But a file name of type File has some very useful methods »exists : tests to see if a file already exists »canRead : tests to see if the operating system will let you read a file FileInputStream and FileOutputStream have constructors that take a File argument as well as constructors that take a String argument The text shows some additional useful File methods l Usage: »File fileObject = new(“numbers.dat”); »File fileObject = new(fileName);

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 31 Unwrapping the Class SavitchIn : The readChar Method public static char readChar() { int charAsInt = -1; try { charAsInt = System.in.read(); } catch (IOException e) { System.out.println(e.getMessage()); System.out.println("Fatal error. Ending Program."); System.exit(0); } return (char)charAsInt; } Returns an int, not a char Initialized to avoid compiler error message.

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 32 Unwrapping the Class SavitchIn : The readLine Method public static String readLine() { char nextChar; String result = ""; boolean done = false; while (!done) { nextChar = readChar(); if (nextChar == '\n') done = true; else if (nextChar == '\r') { } else result = result + nextChar; } return result; } Do nothing. Next iteration will detect '\n' '\r' is carriage return symbol. Some systems use '\r' followed by '\n' to show the end of a line. Add any character except '\r' and '\n' to result string. Definition on previous slide

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 33 Using Path Names l Path name—gives name of file and tells which directory the file is in l Relative path name—gives the path starting with the directory that the program is in l Typical UNIX path name: /user/smith/homework/java/FileClassDemo.java l Typical Windows path name: D:\Work\Java\Programs\FileClassDemo.java l When a backslash is used in a quoted string it must be written as two backslashes since backslash is the escape character: "D:\\Work\\Java\\Programs\\FileClassDemo.java" l Java will accept path names in UNIX or Windows format, regardless of which operating system it is actually running on.

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 34 Summary Part 1 l Text files contain strings of printable characters; they look intelligible to humans when opened in a text editor. l Binary files contain numbers or data in non-printable codes; they look unintelligible to humans when opened in a text editor. l Java can process both binary and text files, but binary files are more common when doing file I/O. The class ObjectOutputStream is used to write output to a binary file.

Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 35 Summary Part 2 The class ObjectInputStream is used to read input from a binary file. l Always check for the end of the file when reading from a file. The way you check for end-of-file depends on the method you use to read from the file. A file name can be read from the keyboard into a String variable and the variable used in place of a file name. The class File has methods to test if a file exists and if it is read- and/or write-enabled. l Serializable class objects can be written to a binary file.