© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 11 - 1 Chapter 11 File Input and Output.

Slides:



Advertisements
Similar presentations
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 12 File Input and Output Animated Version.
Advertisements

Chapter 19 Binary I/O.
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.
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.
File input and output. Interactive vs. file I/O All of the programs we have seen or written thus far have assumed interaction with a user, who types in.
King Saud University College of Computer and Information Sciences Department of Computer Science Dr. S. HAMMAMI Chapter 3 File Input/Output Chapter 3 File.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
Chapter 9 Streams and File I/O Overview of Streams and File I/O
File Input and Output Recitation 04/03/2009 CS 180 Department of Computer Science, Purdue University.
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
Simple Java I/O Part I General Principles. 2 Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Files and Streams CS 21a. 10/02/05 L18: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
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.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
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.
15-Jul-15 Simple Java I/O Part I General Principles.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
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.
Object Input/Output. Object I/O  To write objects to a file, we use ObjectOutputStream  To read objects from a file we use ObjectInputStream  Lets.
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.
Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner,
Files and Streams. Midterm exam Time: Wednesday, October 31, 2007 Format: Multiple choices (about 15 to 20 questions) Determine the results of the code.
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.
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.
Selection sort and Merge sort File input/output. HW 2 – Section 02 Avg = 96/100.
© Amir Kirsh Files and Streams in Java Written by Amir Kirsh.
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.
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.
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,
CSI 3125, Preliminaries, page 1 Files. CSI 3125, Preliminaries, page 2 Reading and Writing Files Java provides a number of classes and methods that allow.
GENERICS AND FILE HANDLING Saumya Srivastava (977934) Divyangana Pandey (977790) Shubhi Saxena (978108) Arka Das (962969) AHD05/15-16 AJA 21.
File Input & Output1 Streams & File I/O. Introduction (1) The Java platform includes a number of packages that are concerned with the movement of data.
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 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.
Recitation File I/O. File I/O File inFile = new File("data.txt"); File inFile = new File (“/Users/sunil/test.txt");
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Introduction to OOP with Java 4th Ed, C. Thomas Wu
OO Design and Programming II I/O: Reading and Writing
CMSC 202 Text File I/O.
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.
CS1101: Programming Methodology
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
I/O Basics.
Accessing Files in Java
Chapter 12 File Input and Output
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
Computer Programming with JAVA
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Presentation transcript:

© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 11 File Input and Output

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Chapter 11 Objectives After you have read and studied this chapter, you should be able to Include a FileDialog object in your program to let the user specify a file. Write bytes to a file and read them back from the file using FileOutputStream and FileInputStream. Write values of primitive data types to a file and read them back from the file using DataOutputStream and DataInputStream. Write text data to a file and read them back from the file using PrintWriter and BufferedReader. Write objects to a file and read them back from the file using ObjectOutputStream and ObjectInputStream. Write exception-handling routines using the try–catch block.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter File Objects To operate on a file, we must first create a File object (from java.io). File inFile = new File(“sample.dat”); File inFile = new File(“C:\\SamplePrograms”, “one.txt”); File inFile = new File (“C:/SamplePrograms/test.dat”); Opens the file sample.dat in the current directory. Opens the file one.txt in the directory C:\SamplePrograms. Notice the use of the escape character \. Opens the file test.dat in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Some File Methods if ( inFile.exists( ) ) { … } if ( inFile.isFile( ) ) { … } File folder = new File(“C:/JavaProjects/Ch11”); String filename[ ] = folder.list( ); for (int i=0; i < filename.length; i++ ){ outputBox.printLine( filename[i] ); } To see if inFile is associated to a real file correctly. To see if inFile is associated to a file or a directory. List the name of all files in the directory C:\JavaProjects\Ch11.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter FileDialog - Open FileDialog is a standard file dialog for selecting a file. FileDialog fileBox = new FileDialog( mainWindow, “Open”, FileDialog.LOAD ); fileBox.setVisible( true ); String filename = fileBox.getFile( );

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter FileDialog - Save FileDialog fileBox = new FileDialog( mainWindow, “Save As”, FileDialog.SAVE ); fileBox.setVisible( true );

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Low-Level File I/O – Output //set up file and stream File outFile = new File("sample1.data"); FileOutputStream outStream = new FileOutputStream( outFile ); //data to save byte[] byteArray = {10, 20, 30, 40, 50, 60, 70, 80}; //write data to the stream outStream.write( byteArray ); //output done, so close the stream (very important here) outStream.close();

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Low-Level File I/O – Input //set up file and stream File inFile = new File("sample1.data"); FileInputStream inStream = new FileInputStream(inFile); //set up an array to read data in int fileSize = (int)inFile.length(); byte[] byteArray = new byte[fileSize]; //read data in and display them inStream.read(byteArray); for (int i = 0; i < fileSize; i++) { outputBox.printLine(byteArray[i]); } //input done, so close the stream inStream.close();

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter High-Level File I/O – Output File outFile = new File("sample2.data"); FileOutputStream outFileStream = new FileOutputStream(outFile); DataOutputStream outDataStream = new DataOutputStream(outFileStream); Primitive data type values are written to outDataStream. Primitive data type values are converted to bytes. Converted bytes are written to the file. outDataStream writeFloat writeInt writeDouble 1 outFileStream 2 outFile 3

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter High-Level File I/O – Input File inFile = new File("sample2.data"); FileInputStream inFileStream = new FileInputStream(inFile); DataInputStream inDataStream = new DataInputStream(inFileStream); Primitive data type values are read from inDataStream. Bytes are converted to primitive data type values. Bytes are read from the file. readFloat readInt readDouble 3 inDataStream 2 inFileStream outFile 1

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Textfile I/O – Output //set up file and stream File outFile = new File("sample3.data"); FileOutputStream outFileStream = new FileOutputStream(outFile); PrintWriter outStream = new PrintWriter(outFileStream); //write values of primitive data types to the stream outStream.println( ); outStream.println( L); //… outStream.println('A'); outStream.println(true); //output done, so close the stream outStream.close();

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Textfile I/O – Input //set up file and stream FileinFile = new File("sample3.data"); FileReaderfileReader = new FileReader(inFile); BufferedReaderbufReader = new BufferedReader(fileReader); String str; //get integer str = bufReader.readLine(); int i = Convert.toInt(str); //read other data in a similar manner //input done, so close the stream bufReader.close();

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Handling Exceptions An exception occurs when any of the semantic constraints of the Java language is violated. An exception is said to be thrown and caught. When our program calls a statement that can throw an exception, we must write a code to either propagate the thrown exception or handle it by the try-block statement.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Propagation Approach Add the phrase throws to the declaration for a method that includes a call to a statement that can throw exceptions. Replace with the actual exception class, such as IOException, EOFException, and so forth. void computeSum (String fileName ) throws IOException { File inFile = new File(fileName); FileInputStream inFileStream = new FileInputStream(inFile); DataInputStream inDataStream = new DataInputStream(inFileStream); //read three integers int i = inDataStream.readInt(); int j = inDataStream.readInt(); int k = inDataStream.readInt(); sum = i + j + k; inDataStream.close(); }

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter try-catch Approach Use the try-catch statement to include the exception- handling routines. void computeSum (String fileName ) { success = true; try { File inFile = new File(fileName); FileInputStream inFileStream = new FileInputStream(inFile); DataInputStream inDataStream = new DataInputStream(inFileStream); //read three integers int i = inDataStream.readInt(); int j = inDataStream.readInt(); int k = inDataStream.readInt(); sum = i + j + k; inDataStream.close(); } catch (IOException e) { success = false; }

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Handling Multiple Exceptions You can have more than one catch clause for each try. try {... } catch (FileNotFoundException e) { success = false; System.out.println("File " + fileName + " does not exist."); } catch (EOFException e) { success = false; System.out.println("Error: " + "Cannot read beyond end of file"); } catch (IOException e) { success = false; System.out.println("General I/O exception is thrown"); }

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Object File I/O It is possible to store objects just as easily as you store primitive data values. We use ObjectOutputStream and ObjectInputStream to save to and load objects from a file. To save objects from a given class, the class declaration must include the phrase implements Serializable. For example, class Person implements Serializable {... }

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Saving Objects FileoutFile = new File("objects.data"); FileOutputStream outFileStream = new FileOutputStream(outFile); ObjectOutputStream outObjectStream = new ObjectOutputStream(outFileStream); Person person = new Person("Mr. Espresso", 20, 'M'); outObjectStream.writeObject( person ); account1= new Account(); bank1 = new Bank(); outObjectStream.writeObject( account1 ); outObjectStream.writeObject( bank1 ); Could save objects from the different classes.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Loading Objects FileinFile = new File("objects.data"); FileInputStream inFileStream = new FileInputStream(inFile); ObjectInputStream inObjectStream = new ObjectInputStream(inFileStream); Person person = (Person) inObjectStream.readObject( ); Account account1 = (Account) inObjectStream.readObject( ); Bank bank1 = (Bank) inObjectStream.readObject( ); Must read in the correct order. Must type cast to the correct object type.

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Saving and Loading Arrays Instead of processing array elements individually, it is possible to save and load the whole array at once. Person[] people = new Person[ N ]; //assume N already has a value //build the people array... //save the array outObjectStream.writeObject ( people ); //load the array Person[ ] people = (Person[ ]) inObjectStream.readObject ( );

© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter Let's try one… Start a program that asks if you want to create or open a file If create: write three different variables to an ASCII file using an InputBox Else Open Save the file When opening the file: Open the file using a dialog Print out the file in an OutputBox