Java How to Program, 8/e ©1992-2010 by Pearson Education, Inc. All Rights Reserved.

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.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
Files Files are used to store long term data. –Typically referred to as persistent data. –A file is a group of related records. –A list of friends addresses.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
 2005 Pearson Education, Inc. All rights reserved Files and Streams.
©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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
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.
Files and Streams (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
CIS 270—Application Development II Chapter 14—Files and Streams.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
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.
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 I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Files and Streams Chapter What You Will Learn Create files Read files Write files Update files.
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.
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.
 Pearson Education, Inc. All rights reserved Files and Streams.
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.
Object Serialization. Sequential-access Text Files Sequential-access files store records In order by the record-key field Java imposes no structure on.
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.
DEPARTMENT OF COMPUTER SCIENCE N.HARIKA. Contents Overview of I/O Streams Character Streams Byte Streams Using the Streams 2.
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
 Pearson Education, Inc. All rights reserved Files and Streams.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
 2005 Pearson Education, Inc. All rights reserved Files and Streams.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Java IO Exploring the java.io package and living to talk about it.
java.io supports console and file I/O
The Java IO System Different kinds of IO Different kinds of operations
CSG2H3 Object Oriented Programming
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
Exception Handling, Reading and Writing in Files, Serialization,
Ch14 Files and Streams OBJECTIVES
Chapter 8: Input and Output
University of Central Florida COP 3330 Object Oriented Programming
I/O Basics.
Chapter 17 Binary I/O 1.
Chapter 13: File Input and Output
Java Programming Course
MSIS 670: Object-Oriented Software Engineering
14 Files and Streams.
Stream Oriented I/O Computer Programming II Dr. Tim Margush
Files and Streams in Java
14 Files and Streams.
Chapter 15 Files, Streams and Object Serialization
Presentation transcript:

Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.

 Java programs perform file processing by using classes from package java.io.  Includes definitions for stream classes  FileInputStream (for byte-based input from a file)  FileOutputStream (for byte-based output to a file)  FileReader (for character-based input from a file)  FileWriter (for character-based output to a file)  You open a file by creating an object of one these stream classes. The object’s constructor opens the file. © by Pearson Education, Inc. All Rights Reserved.

 Can perform input and output of objects or variables of primitive data types without having to worry about the details of converting such values to byte format.  To perform such input and output, objects of classes ObjectInputStream and ObjectOutputStream can be used together with the byte-based file stream classes FileInputStream and FileOutputStream.  The complete hierarchy of classes in package java.io can be viewed in the online documentation at  /docs/api/ja va/io/package-tree.html /docs/api/ja va/io/package-tree.html © by Pearson Education, Inc. All Rights Reserved.

 Class File provides information about files and directories.  Character-based input and output can be performed with classes Scanner and Formatter.  Class Scanner is used extensively to input data from the keyboard. This class can also read data from a file.  Class Formatter enables formatted data to be output to any text-based stream in a manner similar to method System.out.printf. © by Pearson Education, Inc. All Rights Reserved.

 Class File provides four constructors.  The one with a String argument specifies the name of a file or directory to associate with the File object.  The name can contain path information as well as a file or directory name.  A file or directory’s path specifies its location on disk.  An absolute path contains all the directories, starting with the root directory, that lead to a specific file or directory.  A relative path normally starts from the directory in which the application began executing and is therefore “relative” to the current directory. © by Pearson Education, Inc. All Rights Reserved.

 The constructor with two String arguments specifies an absolute or relative path and the file or directory to associate with the File object.  The constructor with File and String arguments uses an existing File object that specifies the parent directory of the file or directory specified by the String argument.  The fourth constructor uses a URI object to locate the file.  A Uniform Resource Identifier (URI) is a more general form of the Uniform Resource Locators (URLs) that are used to locate websites.  Figure 17.1 lists some common File methods. The  / docs/api/j ava/io/File.html / docs/api/j ava/io/File.html © by Pearson Education, Inc. All Rights Reserved.

 A separator character is used to separate directories and files in the path.  On Windows, the separator character is a backslash ( \ ).  On Linux/UNIX, it’s a forward slash ( / ).  Java processes both characters identically in a path name.  When building String s that represent path information, use File.separator to obtain the local computer’s proper separator.  This constant returns a String consisting of one character— the proper separator for the system. © by Pearson Education, Inc. All Rights Reserved.

 To retrieve data sequentially from a file, programs start from the beginning of the file and read all the data consecutively until the desired information is found.  It might be necessary to process the file sequentially several times (from the beginning of the file) during the execution of a program.  Class Scanner does not allow repositioning to the beginning of the file.  The program must close the file and reopen it. © by Pearson Education, Inc. All Rights Reserved.

 The data in many sequential files cannot be modified without the risk of destroying other data in the file.  If the name “ White ” needed to be changed to “ Worthington,” the old name cannot simply be overwritten, because the new name requires more space.  Fields in a text file—and hence records—can vary in size.  Records in a sequential-access file are not usually updated in place. Instead, the entire file is usually rewritten.  Rewriting the entire file is uneconomical to update just one record, but reasonable if a substantial number of records need to be updated. © by Pearson Education, Inc. All Rights Reserved.

 To read an entire object from or write an entire object to a file, Java provides object serialization.  A serialized object is represented as a sequence of bytes that includes the object’s data and its type information.  After a serialized object has been written into a file, it can be read from the file and deserialized to recreate the object in memory. © by Pearson Education, Inc. All Rights Reserved.

 Classes ObjectInputStream and ObjectOutputStream, which respectively implement the ObjectInput and ObjectOutput interfaces, enable entire objects to be read from or written to a stream.  To use serialization with files, initialize ObjectInputStream and ObjectOutputStream objects with FileInputStream and FileOutputStream objects. © by Pearson Education, Inc. All Rights Reserved.

 ObjectOutput interface method writeObject takes an Object as an argument and writes its information to an OutputStream.  A class that implements ObjectOuput (such as ObjectOutputStream ) declares this method and ensures that the object being output implements Serializable.  ObjectInput interface method readObject reads and returns a reference to an Object from an InputStream.  After an object has been read, its reference can be cast to the object’s actual type. © by Pearson Education, Inc. All Rights Reserved.

 Objects of classes that implement interface Serializable can be serialized and deserialized with ObjectOutputStream s and ObjectInputStream s.  Interface Serializable is a tagging interface.  It does not contain methods.  A class that implements Serializable is tagged as being a Serializable object.  An ObjectOutputStream will not output an object unless it is a Serializable object. © by Pearson Education, Inc. All Rights Reserved.

 In a class that implements Serializable, every variable must be Serializable.  Any one that is not must be declared transient so it will be ignored during the serialization process.  All primitive-type variables are serializable.  For reference-type variables, check the class’s documentation (and possibly its superclasses) to ensure that the type is Serializable. © by Pearson Education, Inc. All Rights Reserved.

 The program in Figs –17.21 reads records from a file created by the program in Section and displays the contents. © by Pearson Education, Inc. All Rights Reserved.

 ObjectInputStream method readObject reads an Object from a file.  Method readObject throws an EOFException if an attempt is made to read beyond the end of the file.  Method readObject throws a ClassNotFoundException if the class for the object being read cannot be located. © by Pearson Education, Inc. All Rights Reserved.

 This section overviews additional interfaces and classes (from package java.io ) for byte-based input and output streams and character-based input and output streams. © by Pearson Education, Inc. All Rights Reserved.

 InputStream and OutputStream are abstract classes that declare methods for performing byte-based input and output, respectively.  Pipes are synchronized communication channels between threads.  PipedOutputStream (a subclass of OutputStream ) and PipedInputStream (a subclass of InputStream ) establish pipes between two threads in a program.  One thread sends data to another by writing to a PipedOutputStream.  The target thread reads information from the pipe via a PipedInputStream. © by Pearson Education, Inc. All Rights Reserved.

 A FilterInputStream filters an InputStream, and a FilterOutputStream filters an OutputStream.  Filtering means simply that the filter stream provides additional functionality, such as aggregating data bytes into meaningful primitive-type units.  FilterInputStream and FilterOutputStream are typically extended, so some of their filtering capabilities are provided by their subclasses. © by Pearson Education, Inc. All Rights Reserved.

 A PrintStream (a subclass of FilterOutputStream ) performs text output to the specified stream.  System.out and System.err are PrintStream objects. © by Pearson Education, Inc. All Rights Reserved.

 Usually, programs read data as aggregates of bytes that form int s, float s, double s and so on.  Java programs can use several classes to input and output data in aggregate form.  Interface DataInput describes methods for reading primitive types from an input stream.  Classes DataInputStream and RandomAccessFile each implement this interface to read sets of bytes and process them as primitive-type values. © by Pearson Education, Inc. All Rights Reserved.

 Interface DataOutput describes a set of methods for writing primitive types to an output stream.  Classes DataOutputStream (a subclass of FilterOutputStream ) and RandomAccessFile each implement this interface to write primitive-type values as bytes. © by Pearson Education, Inc. All Rights Reserved.

 Buffering is an I/O-performance-enhancement technique.  With a BufferedOutputStream, each output operation is directed to a buffer  holds the data of many output operations  Transfer to the output device is performed in one large physical output operation each time the buffer fills.  The output operations directed to the output buffer in memory are often called logical output operations.  A partially filled buffer can be forced out to the device at any time by invoking the stream object’s flush method.  Using buffering can greatly increase the performance of an application. © by Pearson Education, Inc. All Rights Reserved.

 With a BufferedInputStream, many “logical” chunks of data from a file are read as one large physical input operation into a memory buffer.  As a program requests each new chunk of data, it’s taken from the buffer.  This procedure is sometimes referred to as a logical input operation.  When the buffer is empty, the next actual physical input operation from the input device is performed. © by Pearson Education, Inc. All Rights Reserved.

 Java stream I/O includes capabilities for inputting from byte arrays in memory and outputting to byte arrays in memory.  A ByteArrayInputStream (a subclass of InputStream ) reads from a byte array in memory.  A ByteArrayOutputStream (a subclass of OutputStream ) outputs to a byte array in memory. © by Pearson Education, Inc. All Rights Reserved.

 A SequenceInputStream (a subclass of InputStream ) logically concatenates several InputStream s  The program sees the group as one continuous InputStream.  When the program reaches the end of one input stream, that stream closes, and the next stream in the sequence opens. © by Pearson Education, Inc. All Rights Reserved.

 The Reader and Writer abstract classes are Unicode two-byte, character-based streams.  Most of the byte-based streams have corresponding character-based concrete Reader or Writer classes. © by Pearson Education, Inc. All Rights Reserved.

 Classes BufferedReader (a subclass of abstract class Reader ) and BufferedWriter (a subclass of abstract class Writer ) enable buffering for character-based streams.  Classes CharArrayReader and CharArrayWriter read and write, respectively, a stream of characters to a char array.  A LineNumberReader (a subclass of Buffered- Reader ) is a buffered character stream that keeps track of the number of lines read. © by Pearson Education, Inc. All Rights Reserved.

 An InputStream can be converted to a Reader via class InputStreamReader.  An OuputStream can be converted to a Writer via class OutputStreamWriter.  Class File-Reader and class FileWriter read characters from and write characters to a file.  Class PipedReader and class PipedWriter implement piped-character streams for transfering data between threads.  Class StringReader b StringWriter read characters from and write characters to String s.  A PrintWriter writes characters to a stream. © by Pearson Education, Inc. All Rights Reserved.

 Class JFileChooser displays a dialog that enables the user to easily select files or directories. © by Pearson Education, Inc. All Rights Reserved.

 JFile-Chooser method setFile-SelectionMode specifies what the user can select from the fileChooser.  JFileChooser static constant FILES_AND_DIRECTORIES indicates that files and directories can be selected.  Other static constants include FILES_ONLY (the default) and DIRECTORIES_ONLY.  Method showOpenDialog displays a JFileChooser dialog titled Open.  A JFileChooser dialog is a modal dialog.  Method showOpenDialog returns an integer specifying which button ( Open or Cancel ) the user clicked to close the dialog.  JFileChooser method getSelectedFile returns the selected file as a File object. © by Pearson Education, Inc. All Rights Reserved.