Chapter 8: Input and Output

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 I. 2 Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses.
Chapter 19 Binary I/O.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Slide 10.1 Advanced Programming 2004, based on LY Stefanus’s Slides Object Serialization Object serialization: the process of converting an object into.
COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.
Standard input, output and error. Lecture Under Construction.
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.
Streams and Files The objectives of this chapter are: To understand the principles of I/O streams and where to use them To understand the options and limitations.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
Algorithm Programming I/O via Java Streams Bar-Ilan University תשס"ח by Moshe Fresko.
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.
Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Java I/O Input: information brought to program from an external source
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
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.
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.
I / O in java. java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader.
Object Persistence and Object serialization CSNB534 Asma Shakil.
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.
A stream is a sequence of data. A stream is a flowing sequence of characters.
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.
1 OOP Lecture 17 I/O and Graphics Signe Ellegård Borch Carsten Schuermann IT University Copenhagen.
Copyright(c) Systems and Computer Engineering, Carleton Univeristy, * Object-Oriented Software Development Unit 13 I/O Stream Hierarchy Case.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
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.
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.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
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.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Generics and file handling Presented by: Abha Kumari Neha Pradip Vhanmane Raj Visa Rashmi Kewlani Suvrat Dixit.
Java IO Exploring the java.io package and living to talk about it.
java.io supports console and file I/O
Sequential files creation & writing
CSG2H3 Object Oriented Programming
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
IO in java.
Ch14 Files and Streams OBJECTIVES
Chapter 17 Binary I/O.
Object Writing in files
University of Central Florida COP 3330 Object Oriented Programming
I/O Basics.
Chapter 17 Binary I/O 1.
Chapter 13: File Input and Output
Programming in Java Files and I/O Streams
Објектно орјентисано програмирање
Java Programming Course
Chapter 17 Binary I/O Dr. Clincy - Lecture.
Stream Oriented I/O Computer Programming II Dr. Tim Margush
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Files and Streams in Java
14 Files and Streams.
CS 240 – Advanced Programming Concepts
David Davenport Spring 2005
Presentation transcript:

Chapter 8: Input and Output Java Programming - Advanced Topics

Objectives In this chapter you will: Perform stream input/ output (I/O) with the core classes in the package java.io Use the standard streams System.in, System.out, and System.err Distinguish between byte-oriented and character-oriented streams

Objectives In this chapter you will: Write code that uses objects of the File class to navigate a file system Select valid constructor arguments for FilterInputStream and FilterOutputStream subclasses from a list of classes in the java.io package

Objectives In this chapter you will: Write appropriate code to read, write, and update files using FileInputStream, FileOutputStream, and RandomAccessFile objects Describe the permanent effects on the file system of constructing and using FileInputStream, FileOutputStream, and RandomAccessFile objects Use object serialization

Programming I/ O Most I/O in the Java platform operates through streams In stream I/O, characters or bytes are read or written sequentially When a file is opened as a stream, all input or output starts at the beginning of the file and proceeds character by character or byte by byte to the end of the file The core classes do not offer much formatting control for the output streams

Programming I/ O The package java.text gathers many of the classes and interfaces for handling local customs You can use the core class DecimalFormat in the package java.text to set patterns for formatting and parsing numbers Not all I/O in the Java platform is stream I/O The package java.io includes the core class RandomAccessFile, which you can use to read and write arbitrary locations within a file without first having to read or write all the bytes or characters that precede that location

Byte-Oriented Stream Classes The hierarchies of the byte-oriented stream classes have a superclass for output and another superclass for input All the classes in these hierarchies extend the input and output superclass directly or indirectly, and ultimately extend Object The classes java.io.InputStream and java.io.OutputStream are the roots of a dual hierarchy that encapsulates most of byte-oriented I/O

Byte-Oriented Stream Classes

Predefined Stream Objects All Java programs can use three stream objects that are defined in the System class of the java.lang package These objects are System.in, System.out, and System.err Class - java.lang.System Purpose - The System class provides the standard stream objects

Predefined Stream Objects Fields System.in - The field System.in is a java.io.BufferedInputStream object System.out - The field System.out is a java.io.PrintStream object System.err - The field System.err is a java.io.PrintStream object print and printIn, which are sets of overloaded methods of the PrintStream class, are particularly useful for console output

Predefined Stream Objects The printin method appends a line separate to its argument to produce a complete line of output The print method does not add the line separate, so you can build up one line of output with several calls of print The methods print and printIn are overloaded to create versions specifically for the primitive types, for char[ ], and for String

Input and Output Methods You perform most byte-oriented I/O operations by calling methods that are defined in the InputStream and OutputStream classes The subclasses of InputStream and OutputStream add value by overriding and overloading these methods for specific circumstances Methods boolean markSupported() - int available() void mark( int readlimit ) - void close() int read() - void reset() long skip(long bytecount )

Input and Output Methods Class - java.io.OutputStream Purpose - The OutputStream class is the superclass of all byte-oriented output streams Constructors - The constructor of this class, OutPutStream(), takes no arguments Methods void close() - void flush() void write (int b ) - void write (byte[ ] bytebuffer ) void write ( byte[ ] bytebuffer, int offset, int count )

Filter Streams A number of classes provide extra functionality in the sense that they add or override methods to preprocess output before actually writing the data, or post-process input after the data has been read These are called filter streams A set of classes that extend FilterInputStream or FilterOutputStream provides them

Filter Streams The class FilterInputStream extends InputStream, and the class FilterOutputStream extends OutputStream These abstract classes are designed to act as wrappers for the InputStream and Outputstream classes To use a filter stream, you must already have an InputStream or an OutputStream object

Byte-Oriented Filter Streams

Other Byte I/O Classes The java.io package defines many classes Extensions of InputStream include the following: The class ByteArrayInputStream lets you read an array of bytes as though it is an InputStream object The class SequenceInputStream provides a mechanism for concatenating the data from two or more InputStream objects into a single, seamless stream The class PipedInputStream implements half of a pipe and is especially useful for communication between threads

Other Byte I/ O Classes Extensions of OutputStream include the following: The class ByteArrayOutputStream sends its output into an object of type byte[ ]. You can use this class to perform your own buffering, or to build an object that another piece of code reads as a ByteArrayInputStream The class PipedOutputStream is the complementary class to PipedInputStream. Together, these two classes comprise a pipe that you can use for communication between threads

File I/O Basics Programming stream I/O to and from files is much like programming stream I/O to and from the console Major differences exist between files and the standard console I/O objects System.in, System.out, and System.err: Before you can use a file, you must associate the file with a FileInputStream or FileOutputStream object If you want to access the data in a file in random-access order, you must open it as a RandomAccessFile, not as a FileInputStream In a network environment, the default security restrictions do not let applets do any file I/O on the client workstation

File I/O Basics When you perform stream I/O on a file, you are actually manipulating either a FileInputStream object or a FileOutputStream object You must set up the association between the object and the actual file in either of two ways: You can pass the name of the files, as a String, to the constructor of the FileInputStream or FileOutputStream class You can create a File object, passing the name of the file to the constructor of the file class. Then, create the stream object and pass the File object as a parameter of the constructor

File I/O Basics Creating a File object has advantages: When you create the File object, you can perform checks, such as whether an input file exists and is read-only or has read-write capabilities The File class provides a level of insulation from platform-dependent conventions such as whether a separator between subfolder names is a forward slash, /, or backslash, \ Using a FileInputStream object makes no physical change to any data stored on disk However, creating a FileOutputStream object or writing to a RandomAccessFile object does modify physical storage

File Navigation Methods The File class gives you more than a way of checking the status of a file before you perform I/O on it The File class does double duty as a representative of both kinds of file system objects Syntax - java.io.File Purpose - The File class encapsulates most of the platform-dependent complexities of files and path names in a portable manner

File Navigation Methods Constructors File( String filename ) File( File folder, String filename ) File ( String folder, String filename ) Methods boolean canRead() boolean canWrite() File createTempFile( String prefix, String suffix ) File createTempFile( String prefix, String suffix, File folder )

File Navigation Methods boolean delete() void deleteOnExit() boolean exists() String getAbsolutePath() String getName() String getParent() File getParentFile() boolean isDirectory() boolean isFile()

File Navigation Methods long lastModified() String [ ] list() String [ ] list(FilenameFilter filter ) File [ ] listFiles() File [ ] listFiles(fileFilter filter ) File [ ] listFiles(FilenameFilter filter ) File[ ] listRoots() boolean mkdir() boolean setReadOnly() URL toURL()

Random-Access File I/O The class RandomAccessFile supports byte-oriented I/O to and from random-access files Use it to read and write data from or to any specified location within a file RandomAccessFile objects are not streams RandomAccessFile combines input and output operations in one class

Character Streams The java.io package has classes that are specifically designed to support character streams The character streams differ from the byte streams mainly in that they operate on the buffered input and output and properly convert each character from the encoding scheme of the native operating system to the Unicode character set used by the Java platform In contrast, InputStream and OutputStream, and the classes that extend them, operate on bytes and arrays of bytes

Character Streams The byte-oriented streams correctly handle only seven-bit ASCII characters, which have the same value as the first 128 Unicode characters The hierarchy of classes that support character streams mirrors the structure of the hierarchy of classes that support byte-oriented streams The superclass of character-oriented input stream I/O is java.io.Reader The corresponding output stream is java.io.Writer

Character Stream Classes

Connecting Byte and Character I/O Classes The Java platform includes adapter classes that bridge between character I/O classes and the byte I/O classes The InputStreamReader and OutputStreamWriter classes perform the adaptation You cannot create a stream object from a Writer object or a Reader object

Using Other Character I/O Classes Extensions of the Reader object include the following: The class CharArrayReader lets you read an array of characters as though it were a Reader object The class StringReader lets you read a String as though it were a Reader object The class PipeReader implements half of a pipe and is especially useful for communication between threads

Using Other Character I/O Classes Extensions of the Writer object include the following: The class CharArrayWriter sends its output into an object of type char[ ] The class StringWriter lets you write to a StringBuffer as though it were a Writer object The class PipedWriter is the complementary class to PipedReader The class PrintWriter is the character I/O equivalent of the PrintStream class

Reading One Token at a Time The class StreamTokenizer is a utility class in java.io that is not related to any of the other classes by inheritance It lets you read a file as a sequence of tokens by encapsulating a Reader object and grouping the stream of input bytes into tokens By default, tokens are delimited by whitespace, but you can call many methods to customize a tokenizing algorithm

Reading One Token at a Time Whitespace is any combination of space, new line, or tab characters To use the StreamTokenizer class, first create a Reader object, and then pass the Reader object as a parameter to the constructor of the StreamTokenizer object

Object Serialization Serializing an object to do the following: Transmit objects over a network Save objects to files between runs of your program, or perhaps write and then read objects later in the same application For the primitive types, the byte-oriented filter classes DataOutputStream and DataInputStream provide methods to write and read binary representations of variables of all the primitive types o String objects to and from a file

Object Serialization Object serialization is a general solution that lets you write objects to I/O streams and then read them, without defining any additional methods Object serialization properly handles not only the fields defined in the class, but also inherited fields and any subfields that these fields may have The object serialization feature is an important component of the Java Remote Method Invocation (RMI) enterprise API

Serializing Objects Not all classes of objects support serialization By default, classes are not serializable To let instance of a class be serialized, define the class with implements Serializable The Serializable interface, like Cloneable, is a marker interface and contains no methods Most of the classes in the java.lang package implement the Serializable interface

Serializing Objects Commonly used classes in the java.lang package that do not implement Serializable are Math, Process, Runtime, SecurityManager, System, Thread, ThreadGroup, and Void These omissions make sense for the following reasons: Math and System contain only methods and variables Void is just a placeholder and is essentially empty The nature of the other classes is incompatible with the rationale for object serialization. The Process, Runtime, SecuityManage, Thread, and ThreadGroup objects are used as a program runs

Using Object Streams Two stream classes support object serialization: ObjectOutputStream is a subclass of OutputStream. To create an ObjectOutputStream, provide an existing OutputStream object as the argument of the constructor ObjectInputStream is a subclass of InputStream. To create an ObjectInputStream, provide an existing InputStream object as the argument of the constructor

Suppressing Serialization of Fields Java does not require that every field in a class be serialized Others may be references to objects of classes that do not implement Serializable You can include the qualifier transient when you declare fields to indicate that they should not be serialized with instances of the class When the object is deserialized later, transient fields are given the default value normally used for fields of their type

Suppressing Serialization of Fields You can use the transient qualifier to indicate that certain fields of a class should never be serialized, but it is not very flexible Java provides an alternate approach for runtime control: You can add a private static final field with the name serialPersistentFields and type ObjectStreamField[ ] to the class Programmers are sure to want some ability to customize serialization for a particular class

Suppressing Serialization of Fields Designers have given you two additional methods for this purpose: The readObject and writeObject methods are not part of any interface to be implemented or class to be extended Even though the serialization support calls readObject and writeObject, they must be private methods You must define readObject and writeObject as in the following lines, taken from example program Make sure to call the defaultReadObject and defaultWriteObject methods in customized methods and they do the actual serialization work

Specifying the Version Number You do not make up a version number The value is calculated using a formula that takes the name of the class and its interfaces, fields, and methods You can determine the value with the serialver tool supplied with the SDK, by entering the following command: serialver class_name You can use cut and paste techniques to edit this number into your class definition Alternatively, you may prefer not to define a serialVersionUID field and let the JVM generate one

Compatibility of Serialization Formats The object serialization classes of the Java 2 platform write objects to object streams using a different format from earlier version of the Java platform To identify the serialization stream format used, Java 2 defines two new constants, PROTOCOL_VERSION_1 and PROTOCOL_VERSION_2, in the java.io.ObjectStreamConstants interface

Chapter Summary Most input to and output from the JVM is stream-based, regardless of whether your program is communicating with the console, files, or another program running on your network Support for I/O is provided by the core classes in the package java.io For byte-oriented I/O, the two classes InputStream and OutputStream are the abstract classes that are the roots of input and output class hierarchies, respectively

Chapter Summary The predefined console input stream object, and System.in, and the console output stream objects, System.out and System.err, are InputStream and OutputStream objects The stream I/O model means that console I/O and file I/O are very similar FileInputStream and FileOutputStream are the classes used for reading and writing files File objects are constructed by providing a string containing a filename in a platform-independent manner

Chapter Summary Filter stream classes are designed to wrap either an InputStream or an OutputStream class Several other classes extend the InputStream and OutputStream classes to provide capabilities such as reading and writing byte arrays, sequencing multiple streams as a single stream, and reading and writing pipes Use the class RandomAccessFile to read and write information at arbitrary locations within a file without first having to read or write information at the preceding locations

Chapter Summary To enable programmers to read and write objects as whole, the Java programming language provides Object serialization Only classes that implement the marker interface Serializable can be serialized You can exclude individual fields within a class from the serialization operation by applying the transient qualifier