COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
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.
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.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
©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.
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 in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
©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.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
COMP201 Java Programming Topic 6: Streams and Files Reading: Chapter 12.
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 I/O Input: information brought to program from an external source
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
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.
Streams and Files CMPS Overview Stream classes File objects File operations with streams Examples in C++ and Java 2.
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.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
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 How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
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,
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
MIT AITI 2003 Lecture 15 Streams Input and Output data from/to other sources.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture.
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
Two Ways to Store Data in a File  Text format  Binary format.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
Read and Write Files  By the end of this lab you will be able to:  Write a file in internal storage  Read a file from internal storage  Write a file.
Outline  Basic IO  File class  The Stream Zoo  Serialization  Regular Expressions.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
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.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
CS 116 Object Oriented Programming II Lecture 11 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
The Java IO System Different kinds of IO Different kinds of operations
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Lecture 8: I/O Streams types of I/O streams Chaining Streams
CSG2H3 Object Oriented Programming
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
I/O Basics.
Streams and File I/O Chapter 9 Chapter 9.
Streams and File I/O Chapter 14.
JAVA IO.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Java Basics Introduction to Streams.
CS 240 – Advanced Programming Concepts
Chapter 8: Exceptions and I/O Streams
Presentation transcript:

COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12

COMP201 Topic 6 / Slide 2 Objectives and Outline l Objectives: n Overall view i/o in java n Reading and writing local files l Outline n Introduction and overview n Reading and writing local files –Connecting to files –Reading and writing characters –Reading and writing objects n File management

COMP201 Topic 6 / Slide 3 Introduction and Overview l When talking about IO, we need to consider files n At different locations: –blocks of main memory – local file system – over the net n In different formats: –text or binary – zipped or not zipped n With different access modes: –plain sequential, –buffered, –pushback, –Random

COMP201 Topic 6 / Slide 4 l Java streams n Input streams: –Objects from where we read input sequences n Output stream: –Objects where we write output sequences l Java has stream classes allow us to deal with all possible combinations of location, format, and access mode. l In particular, Java streams provide an abstraction of files at different locations n Local files and files from internet can be handled the same way. n We discuss only local files in this lecture. l In the next few slides, we give some of the stream classes Introduction and Overview

COMP201 Topic 6 / Slide 5 Introduction and Overview All classes for reading from character streams inherit from abstact class Reader Reader has one abstract method read, which returns the next unicode character or –1 (EOF) Reader LineNumber Reader Pushback Reader InputStream Reader CharArray Reader Filter Reader Buffered Reader String Reader Piped Reader File Reader

COMP201 Topic 6 / Slide 6 Introduction and Overview All classes for writing character streams inherit from abstact class Writer Writer has one abstract method write(int b), which writes a unicode charater to an output Writer Print Writer File Writer Buffered Writer OutputStream Writer Piped Writer Filter Writer CharArray Writer String Writer

COMP201 Topic 6 / Slide 7 Introduction and Overview All classes for reading from byte streams inherit from abstact class InputStream InputStream has one abstract method read, which returns the next byte character or –1 (EOF) InputStream Pushback InputStream LineNumber InputStream Data InputStream Buffered InputStream File InputStream ByteArray InputStream Filter InputStream Sequence InputStream StringBuffer InputStream Object InputStream Piped InputStream..

COMP201 Topic 6 / Slide 8 Introduction and Overview All classes for writing to byte streams inherit from abstact class OutputStream OutputStream has one abstract method write(int b), which writes one byte to an output OutputStream Checked OutputStream PrintStream Data OutputStream Buffered OutputStream ByteArray OutputStream Filter OutputStream Object OutputStream Piped OutputStream.. File OutputStream

COMP201 Topic 6 / Slide 9 Reading and Writing local files l Plan –Connecting to files: open files –Reading and writing characters l Parsing –Reading and writing objects

COMP201 Topic 6 / Slide 10 Connecting to Files l Open a file for writing bytes n FileOutputStream out = new FileOutputStream(“employee.dat”); FileOutputStream has method for writing bytes: out.write(int b); n Seldom write individual bytes write method used by higher level streams l Open a file for reading bytes FileInputStream in = new FileInputStream(“employee.dat”); FileInputStream has method for reading bytes in.read(); n Seldom read individual bytes read method used by higher level streams

COMP201 Topic 6 / Slide 11 Writing Characters An OutputStreamWriter is a bridge from character streams to byte streams Has method for writing character: void write(int c) Nesting OutputStreamWriter with FileOutputStream allows us to write individual characters to files n OutputStreamWriter out = new OutputStreamWriter (new FileOutputStream(“employee.dat”) ); If out.write(‘a’), out.flush() then ‘a’ goes to the file (“employee.dat”). –Two classes in action here l One converts ‘a’ into bytes l One write bytes to file

COMP201 Topic 6 / Slide 12 Writing Characters The combination of OutputStreamWriter and FileOutputStream is commonly used. A convenience class FileWriter is hence introduced FileWriter f = new FileWriter(“employee.dat”); is equivalent to OutputStreamWriter f = new OutputStreamWriter( new FileOutputStream(“employee.dat”));

COMP201 Topic 6 / Slide 13 Writing Charaters l Seldom write characters one by one n Usually write strings. How to write Strings? PrintWriter prints formatted representations of objects to a text-output stream Has methods print and println. l Example n PrintWriter out = new PrintWriter( new FileWriter(“employee.dat”)); If out.println(“this is a test”), – then the string “this is a test” goes to file “employee.dat” n Three classes in action here –PrintWriter breaks the string into characters – OutputStreamWriter converts characters into bytes –FileOutputStream writes bytes to file WriteTextTest.java

COMP201 Topic 6 / Slide 14 Reading Characters l For writing we have n FileOutputStream, OutputStreamWriter, FileWriter, PrintWriter For reading we have n FileInputStream, InputStreamReader, FileReader, BufferedReader BufferedReader has method readLine for reading one line ReadTextTest.java

COMP201 Topic 6 / Slide 15 Read and Write Standard IO System.out predefined PrintStream, stands for screen. l Print to screen: l System.out.print(); System.out.println(); System.in predefined InputStream, stands for keyboard. Nest System.in with BufferedReader Use method readLine l Example: Echo.java

COMP201 Topic 6 / Slide 16 Parsing l Reading a text file / Parsing input s=readLine() gives you a long string. l Need to break the string into individual strings and convert them into proper type. To do this, use the StringTokenizer class in java.util. Create a StringTokenizer object for the delimiter “|” String Tokenizer t = new StringTokenizer(s, “|”);

COMP201 Topic 6 / Slide 17 Parsing Reading a text file / Parsing input Use the nextToken method to extract the next piece from string. t.nextToken () --- name. t.nextToken() --- salary as string. Need Double.parseDouble t.nextToken() --- year as string. Need Integer.parseInt t.nextToken() --- month as string. Need Integer.parseInt t.nextToken() --- day as string. Need Integer.parseInt l Here we know that there are 5 tokens on each line. In general, call t.hasMoreTokens before each t.nextToken Use StreamTokenizer to parse a file DataFileTest.java

COMP201 Topic 6 / Slide 18 Reading and Writing Objects l When useful n Need to save some information and retrieve it later. n Saved information does not have to be human readable. l Why bother (since we can write and read text files) n Much easier than writing and reading text files

COMP201 Topic 6 / Slide 19 Writing Objects To save an object, open an ObjectOutputStream ObjectOutputStream out = new ObjectOutputStream ( new FileOutputStream(“employee.dat”)); Simply use writeObject method to save an object Employee harry = new Employee("Harry Hacker", 35000, new Day(1989,10,1)); Manager carl = new Manager("Carl Cracker", 75000, new Day(1987,12,15)); out.writeObject(harry); out.writeObject(carl);

COMP201 Topic 6 / Slide 20 Reading Objects To get back an object, open an ObjectInputStream ObjectInputStream in = new ObjectInputStream ( new FileInputStream(“employee.dat”)); Use readObject method to retrieve objects in the same order in which they were written Employee e1 = (Employee) in.readObject(); Employee e2 = (Employee) in.readObject(); Cast necessary because readObject returns an object of class Object.

COMP201 Topic 6 / Slide 21 Serializable Interface l For object writing/reading to work, the class must implement the serializable interface n Class Employee implements Serializable(){…} l Since Arrays, one can write/read an array of any objects in one sentence n Employee[] staff; … n out.writeObject( staff ); n (Employee[])in.readObject(); ObjectFileTest.java

COMP201 Topic 6 / Slide 22 File Management Use java.io.File l Creating a new directory: Create a File object File tempDir = new File( “temp”); n Create directory tempDir.mkdir(); l Creating a new file n Create a File object: File foo = new File(“dirName”+File.separator + “data.txt”); File foo = new File(“dirName”, “data.txt”); n Create file foo.createNewFile();

COMP201 Topic 6 / Slide 23 File Management l Inspecting contents of a directory someDir.list() returns an array of file names under the directory l Deleting files and directories someDir.delete(); someFile.delete(); FindDirectories.java