Chapter 17 Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams  Use JFileChooser F Text Input.

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

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.
1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
Chapter 19 Binary I/O.
Lecture 15: I/O and Parsing
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.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 18 Binary 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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
INF120 Basics in JAVA Programming AUBG, COS dept, Fall semester 2013 Reference books: Malik D.S., Java Programming, From Problem Analysis to Program Design,
Introduction to Java Y.Daniel Liang
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 19 Binary I/O.
Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Use JFileChooser F Text Input.
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香.
Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
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.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
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.
L5: Input & Output COMP206, Geoff Holmes and Bernhard Pfahringer.
Two Ways to Store Data in a File  Text format  Binary format.
Java Input/Output. Reading standard input Surprisingly complicated (GUI focus) Old-fashioned way: BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
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.
A stream is a sequence of data. A stream is a flowing sequence of characters.
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.
Copyright(c) Systems and Computer Engineering, Carleton Univeristy, * Object-Oriented Software Development Unit 13 I/O Stream Hierarchy Case.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Binary I/O.
1 Chapter 19 Binary I/O. 2 Motivations F Data stored in a text file – is represented in human-readable form –Text file –Readable –Java source programs.
Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Parsing Text Files F Random.
Chapter 15: Input and Output
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Files in Java 1.
1 Chapter 16 Simple Input and Output. 2 Objectives F To discover file properties, delete and rename files using the File class (§16.2). F To understand.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
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.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Java Programming, Second Edition Chapter Sixteen File Input and Output.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
Java IO Exploring the java.io package and living to talk about it.
Chapter 10: I/O Streams Input Streams Output Streams
The Java IO System Different kinds of IO Different kinds of operations
Fundamental of Java Programming
IO in java.
IO in java.
Chapter 17 Input and Output
Chapter 17 Binary I/O.
Object Writing in files
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
I/O Basics.
Chapter 17 Binary I/O 1.
Streams and File I/O Chapter 9 Chapter 9.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
Chapter 16 Simple Input and Output
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
The Package Statement Group related interfaces and classes together
David Davenport Spring 2005
Presentation transcript:

Chapter 17 Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams  Use JFileChooser F Text Input and Output on the Console F Object Streams F Random Access Files F Parsing Text Files

Streams F A stream is an abstraction of the continuous one-way flow of data.

Stream Classes F The stream classes can be categorized into two types: byte streams and character streams.  The InputStream/OutputStream class is the root of all byte stream classes, and the Reader/ Writer class is the root of all character stream classes. The subclasses of InputStream/ OutputStream are analogous to the subclasses of Reader/Writer.

Byte Stream Classes

Character Stream Classes

InputStream F abstract int read() throws IOException F int read(byte[] b) throws IOException F void close() throws IOException F int available() throws IOException F long skip(long n) throws IOException

Reader The Reader class is similar to the InputStream class. The methods in Reader are subject to character interpretation. F abstract int read() throws IOException F int read(char b[]) throws IOException F void close() throws IOException F void skip() throws IOException

OutputStream F abstract void write(int b) throws IOException F void write(byte[] b) throws IOException F void close() throws IOException F void flush() throws IOException

Writer F abstract void write(int b) throws IOException F void write(char[] b) throws IOException F void close() throws IOException F void flush() throws IOException

Processing External Files You must use file streams to read from or write to a disk file. You can use FileInputStream or FileOutputStream for byte streams, and you can use FileReader or FileWriter for character streams.

File I/O Stream Constructors Constructing instances of FileInputStream, FileOutputStream, FileReader, and FileWriter from file names: FileInputStream infile = new FileInputStream("in.dat"); FileOutputStream outfile = new FileOutputStream("out.dat"); FileReader infile = new FileReader("in.dat"); FileWriter outfile = new FileWriter("out.dat");

Example 17.1 Processing External Files CopyFileUsingByteStream Run

Data Streams The data streams ( DataInputStream and DataOutputStream ) read and write Java primitive types in a machine-independent fashion, which enables you to write a data file in one machine and read it on another machine that has a different operating system or file structure.

DataInputStream Methods F int readByte() throws IOException F int readShort() throws IOException F int readInt() throws IOException F int readLong() throws IOException F float readFloat() throws IOException F double readDouble() throws IOException F char readChar() throws IOException F boolean readBoolean() throws IOException F String readUTF() throws IOException

DataOutputStream Methods F void writeByte(byte b) throws IOException F void writeShort(short s) throws IOException F void writeInt(int i) throws IOException F void writeLong(long l) throws IOException F void writeFloat(float f) throws IOException F void writeDouble(double d) throws IOException F void writeChar(char c) throws IOException F void writeBoolean(boolean b) throws IOException F void writeBytes(String l) throws IOException F void writeChars(String l) throws IOException F void writeUTF(String l) throws IOException

Data I/O Stream Constructors F DataInputStream in = new DataInputStream(inputstream); DataInputStream infile = new DataInputStream( new FileInputStream("in.dat")); Creates a data input stream for file in.dat. F DataOutputStream out = new DataOutputStream(outputstream); DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat")); Creates a data output stream for file out.dat.

Example 17.2 Using Data Streams TestDataStream Run

Print Streams The data output stream outputs a binary represen- tation of data, so you cannot view its contents as text. In Java, you can use print streams to output data into files. These files can be viewed as text. The PrintStream and PrintWriter classes provide this functionality.

PrintWriter Constructors F PrintWriter(Writer out) F PrintWriter(Writer out, boolean autoFlush) F PrintWriter(OutputStream out) F PrintWriter(OutputStream out, boolean autoFlush)

PrintWriter Methods F void print(Object o) F void print(String s) F void println(String s) F void print(char c) F void print(char[] cArray) F void print(int i) F void print(long l) F void print(float f) F void print(double d) F void print(boolean b)

Example 17.3 Using Print Streams Run TestPrintWriter

Buffered Streams Java introduces buffered streams that speed up input and output by reducing the number of reads and writes. In the case of input, a bunch of data is read all at once instead of one byte at a time. In the case of output, data are first cached into a buffer, then written all together to the file. Using buffered streams is highly recommended.

Buffered Stream Constructors F BufferedInputStream (InputStream in) F BufferedInputStream (InputStream in, int bufferSize) F BufferedOutputStream (OutputStream in) F BufferedOutputStream (OutputStream in, int bufferSize) F BufferedReader(Reader in) F BufferedReader(Reader in, int bufferSize) F BufferedWriter(Writer out) F BufferedWriter(Writer out, int bufferSize)

Example 17.4 Displaying a File in a Text Area F Objective: View a file in a text area. The user enters a filename in a text field and clicks the View button; the file is then displayed in a text area. ViewFile Run

Example 17.5 Using File Dialogs F Objective: Create a simple notepad using JFileChooser to open and save files. The notepad enables the user to open an existing file, edit the file, and save the note into the current file or to a specified file. You can display and edit the file in a text area. RunFileDialogDemo Note: You cannot run this from the CD; the program writes to disk.

Text Input and Output on the Consoles There are two types of interactive I/O. One involves simple input from the keyboard and simple output in a pure text form. The other involves input from various input devices and output to a graphical environment on frames and applets. The former is referred to as text interactive I/O, and the latter is known as graphical interactive I/O.

Console Output/Input To perform console output, you can use any of the methods for PrintStream in System.out. However, keyboard input is not directly supported in Java. In order to get input from the keyboard, you first use the following statements to read a string from the keyboard. MyInput

Object Streams Object streams enable you to perform input and output at the object level. To enable an object to be read or write, the object's defining class has to implement the java.io.Serializable interface or the java.io.Externalizable interface.

The Serializable Interface The Serializable interface is a marker interface. It has no methods, so you don't need to add additional code in your class that implements Serializable. Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays.

The Object Streams You need to use the ObjectOutputStream class for storing objects and the ObjectInputStream class for restoring objects. These two classes are built upon several other classes.

The ObjectOutput and ObjectInput Streams

Example 17.6 Testing Object Streams  Objective: Stores objects of MessagePanel and Date, and Restores these objects. RunObjectStreamDemo Note: You cannot run this from the CD; the program writes to disk.

Random Access Files  Java provides the RandomAccessFile class to allow a file to be read and updated at the same time.  The RandomAccessFile class extends Object and implements DataInput and DataOutput interfaces.

RandomAccessFile Methods Many methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream. For example, readInt(), readLong(), writeDouble(), readLine(), writeInt(), and writeLong() can be used in data input stream or data output stream as well as in RandomAccessFile streams.

RandomAccessFile Methods, cont. F void seek(long pos) throws IOException; Sets the offset from the beginning of the RandomAccessFile stream to where the next read or write occurs. F long getFilePointer() IOException; Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs.

RandomAccessFile Methods, cont. F long length()IOException Returns the length of the file. F final void writeChar(int v) throws IOException Writes a character to the file as a two-byte Unicode, with the high byte written first.  final void writeChars(String s) throws IOException Writes a string to the file as a sequence of characters.

RandomAccessFile Constructor RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); //allows read and write RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); //read only

Example Using Random Access Files F Objective: Create a program that registers students and displays student information. Run TestRandomAccessFile Note: You cannot run this from the CD; the program writes to disk.

Parsing Text Files (Optional) The StreamTokenizer class lets you take an input stream and parse it into words, which are known as tokens. The tokens are read one at a time. The following is the StreamTokenizer constructor: StreamTokenizer st = StreamTokenizer(Reader is)

StreamTokenizer Constants F TT_WORD The token is a word. F TT_NUMBER The token is a number.  TT_EOL The end of the line has been read.  TT_EOF The end of the file has been read.

StreamTokenizer Variables F int ttype Contains the current token type, which matches one of the constants listed on the preceding slide. F double nval Contains the value of the current token if that token is a number. F String sval Contains a string that gives the characters of the current token if that token is a word.

StreamTokenizer Methods public int nextToken() throws IOException Parses the next token from the input stream of this StreamTokenizer. The type of the next token is returned in the ttype field. If ttype == TT_WORD, the token is stored in sval ; if ttype == TT_NUMBER, the token is stored in nval.

Example 17.8 Using StreamTokenizer Run ParsingTextFile Click the Run button to access the DOS prompt; then type java ParsingTextFile and press Enter. (Note: You cannot run this from the CD; the program writes to disk.)