Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Similar documents
Data stored in variables and arrays is temporary

Chapter 4 Java I/O. X i a n g Z h a n g j a v a c o s q q. c o m

The Java I/O System. Binary I/O streams (ASCII, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Software 1 with Java. Recitation No. 9 (Java IO) December 10,

Software 1 with Java. Recitation No. 7 (Java IO) May 29,

Software 1. Java I/O

Example: Copying the contents of a file

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

Exceptions and Working with Files

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

CS 251 Intermediate Programming Java I/O Streams

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

CSC 1214: Object-Oriented Programming

Object-Oriented Programming in the Java language

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

File. Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices

Writing usable APIs in practice

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

Java Input / Output. CSE 413, Autumn 2002 Programming Languages.

Files and Streams

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7)

CSB541 Network Programming 網路程式設計. Ch.2 Streams 吳俊興國立高雄大學資訊工程學系

The I/O Package. THE Java platform includes a number of packages that are concerned with the CHAPTER20

C17: I/O Streams and File I/O

Chapter 17 Binary I/O. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

Software 1. תרגול 9 Java I/O

File Input/Output. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166

C17: File I/O and Exception Handling

Software 1 with Java. The java.io package. Streams. Streams. Streams. InputStreams

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

Special error return Constructors do not have a return value What if method uses the full range of the return type?

Data Structures. 03 Streams & File I/O

CPS122 Lecture: Input-Output

I/O Streams. Object-oriented programming

Lecture 7. File Processing

CS112 Lecture: Streams

Lecture 11.1 I/O Streams

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

Active Learning: Streams

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

Objec&ves STANDARD ERROR. Standard Error Streams. Ø Byte Streams Ø Text Streams 10/5/16. Oct 5, 2016 Sprenkle - CSCI209 1

输 入输出相关类图. DataInput. DataOutput. java.lang.object. FileInputStream. FilterInputStream. FilterInputStream. FileOutputStream

Streams and File I/O

Java IO and C++ Streams

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

CPS122 Lecture: Input-Output

PIC 20A Streams and I/O

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

CSD Univ. of Crete Fall Files, Streams, Filters

Writing usable APIs in practice

Core Java Contents. Duration: 25 Hours (1 Month)

Darshan Institute of Engineering & Technology for Diploma Studies

1.00 Lecture 30. Sending information to a Java program

Objec&ves. Review. Standard Error Streams

Pieter van den Hombergh Richard van den Ham. March 13, 2018

Programming Languages and Techniques (CIS120)

Chapter 10. IO Streams

Java Programming Lecture 9

Princeton University COS 333: Advanced Programming Techniques A Subset of Java

Software 1. The java.io package. Streams. Streams. Streams. InputStreams

Object-Oriented Programming Design. Topic : Streams and Files

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Object Oriented Design with UML and Java. PART VIII: Java IO

Algorithms. Produced by. Eamonn de Leastar

ITI Introduction to Computer Science II

HST 952. Computing for Biomedical Scientists Lecture 8

Chapter 12. File Input and Output. CS180-Recitation

I/O streams. Byte Streams Character Streams InputStream ByteArrayInputStream FileInputStream FilterInputStream

Byte and Character Streams. Reading and Writing Console input and output

Streams. Programação Orientada por Objetos (POO) Centro de Cálculo Instituto Superior de Engenharia de Lisboa

Chapter 8: Files and Security

CPIT 305 Advanced Programming

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

Basic Java IO Decorator pattern Advanced Java IO. Java IO - part 2 BIU OOP. BIU OOP Java IO - part 2

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

Complete Java Contents

ROEVER ENGINEERING COLLEGE Elambalur,Perambalur DEPARTMENT OF CSE

pre-emptive non pre-emptive

IT101. File Input and Output

Advanced Object-Oriented Programming Streams and Files

Simple Java Input/Output

Java Input/Output. 11 April 2013 OSU CSE 1

Programming Languages and Techniques (CIS120)

Performing input and output operations using a Byte Stream

Chapter 10 Input Output Streams

Programming Languages and Techniques (CIS120)

Streams and File I/O

Chapter 11: Exceptions and Advanced File I/O

System.out.format("The square root of %d is %f.%n", i, r);

10.1 Overview 162 CHAPTER 10 CHARACTER STREAMS

How to access your database from the development environment. Marco Ronchetti Università degli Studi di Trento

Chapter 12: Exceptions and Advanced File I/O

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Transcription:

Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.

Data stored in variables and arrays is temporary It s lost when a local variable goes out of scope or when the program terminates For long-term retention of data, computers use files. Computers store files on secondary storage devices hard disks, optical disks, flash drives and magnetic tapes. Data maintained in files is persistent data because it exists beyond the duration of program execution. Copyright 1992-2012 by Pearson

The techniques shown in this chapter are based on Java SE 6. Java SE 7 introduces new file-system APIs for interacting with files and directories. Copyright 1992-2012 by Pearson

Java views each file as a sequential stream of bytes (Fig. 17.1). Every operating system provides a mechanism to determine the end of a file, such as an end-of-file marker or a count of the total bytes in the file that is recorded in a system-maintained administrative data structure. A Java program simply receives an indication from the operating system when it reaches the end of the stream Copyright 1992-2012 by Pearson

File streams can be used to input and output data as bytes or characters. Streams that input and output bytes are known as bytebased streams, representing data in its binary format. Streams that input and output characters are known as character-based streams, representing data as a sequence of characters. Files that are created using byte-based streams are referred to as binary files. Files created using character-based streams are referred to as text files. Text files can be read by text editors. Binary files are read by programs that understand the specific content of the file and the ordering of that content. Copyright 1992-2012 by Pearson

A Java program opens a file by creating an object and associating a stream of bytes or characters with it. Can also associate streams with different devices. Java creates three stream objects when a program begins executing System.in (the standard input stream object) normally inputs bytes from the keyboard System.out (the standard output stream object) normally outputs character data to the screen System.err (the standard error stream object) normally outputs character-based error messages to the screen. Class System provides methods setin, setout and seterr to redirect the standard input, output and error streams, respectively. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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 http://download.oracle.com/javase/6/docs/ api/java/io/package-tree.html Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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.2 lists some common File methods. The http://download.oracle.com/javase/6/docs/ api/java/io/file.html Copyright 1992-2012 by Pearson

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 Strings 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. Copyright 1992-2012 by Pearson

Sequential-access files store records in order by the record-key field. Text files are human-readable files. Copyright 1992-2012 by Pearson

Java imposes no structure on a file Notions such as records do not exist as part of the Java language. You must structure files to meet the requirements of your applications. Copyright 1992-2012 by Pearson

Formatter outputs formatted Strings to the specified stream. The constructor with one String argument receives the name of the file, including its path. If a path is not specified, the JVM assumes that the file is in the directory from which the program was executed. If the file does not exist, it will be created. If an existing file is opened, its contents are truncated. Copyright 1992-2012 by Pearson

A SecurityException occurs if the user does not have permission to write data to the file. A FileNotFoundException occurs if the file does not exist and a new file cannot be created. static method System.exit terminates an application. An argument of 0 indicates successful program termination. A nonzero value, normally indicates that an error has occurred. The argument is useful if the program is executed from a batch file on Windows or a shell script on UNIX/Linux/Mac OS X. Copyright 1992-2012 by Pearson

Scanner method hasnext determines whether the endof-file key combination has been entered. A NoSuchElementException occurs if the data being read by a Scanner method is in the wrong format or if there is no more data to input. Formatter method format works like System.out.printf A FormatterClosedException occurs if the Formatter is closed when you attempt to output. Formatter method close closes the file. If method close is not called explicitly, the operating sys-tem normally will close the file when program execution terminates. Copyright 1992-2012 by Pearson

Different platforms use different line-separator characters. On UNIX/Linux-/Mac OS X, the line separator is a newline (\n). On Windows, it is a combination of a carriage return and a line feed represented as \r\n. You can use the %n format specifier in a format control string to output a platform-specific line separator. Method System.out.println outputs a platformspecific line separator after its argument. Regardless of the line separator used in a text file, a Java program can still recognize the lines of text and read them. Copyright 1992-2012 by Pearson

The application in Figs. 17.9 and 17.10 reads records from the file "clients.txt" created by the application of Section 17.4.1 and displays the record contents. Copyright 1992-2012 by Pearson

If a Scanner is closed before data is input, an IllegalStateException occurs. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

Objects of classes that implement interface Serializable can be serialized and deserialized with ObjectOutputStreams and ObjectInputStreams. 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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

The program in Figs. 17.18 17.19 reads records from a file created by the program in Section 17.5.1 and displays the contents. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

A PrintStream (a subclass of FilterOutputStream) performs text output to the specified stream. System.out and System.err are PrintStream objects. Copyright 1992-2012 by Pearson

Usually, programs read data as aggregates of bytes that form ints, floats, doubles 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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

A SequenceInputStream (a subclass of InputStream) logically concatenates several InputStreams 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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson

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 bstringwriter read characters from and write characters to Strings. A PrintWriter writes characters to a stream. Copyright 1992-2012 by Pearson

Class JFileChooser displays a dialog that enables the user to easily select files or directories. Copyright 1992-2012 by Pearson

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. Copyright 1992-2012 by Pearson