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.

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 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.
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.
Lecture 31 File I/O -Part 2 COMP1681 / SE15 Introduction to Programming.
Unit 211 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
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.
Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,
© The McGraw-Hill Companies, 2006 Working with files Chapter 20.
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.
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.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
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.
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.
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.
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 与人玫瑰,手有余香.
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.
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: 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.
Binary Files, Random Access Files Binary Files The way data is stored in memory is sometimes called the raw binary format. Data can be stored in.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
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.
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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 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 Parsing Text Files F Random.
Chapter 15: Input and Output
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
BINARY I/O IN JAVA CSC 202 November What should be familiar concepts after this set of topics: All files are binary files. The nature of text files.
IO in java.
Chapter 17 Input and Output
Ch14 Files and Streams OBJECTIVES
Chapter 17 Binary I/O.
Object Writing in files
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Chapter 17 Binary I/O 1.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
MSIS 670: Object-Oriented Software Engineering
Chapter 16 Simple Input and Output
Chapter 17 Binary I/O.
David Davenport Spring 2005
Presentation transcript:

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 are stored in text files F Data stored in a binary file – is represented in binary form –Binary file –Cannot read binary files –Designed to be read by programs –Java classes are stored in binary files –Readable by the JVM –Advantage of binary files u More efficient to process than text files

3 Objectives F To discover how I/O is processed in Java (§19.2). F To distinguish between text I/O and binary I/O (§19.3). F To read and write bytes using FileInputStream and FileOutputStream (§19.4.1). F To read and write primitive values and strings using DataInputStream/DataOutputStream (§19.4.3). F To store and restore objects using ObjectOutputStream and ObjectInputStream, and to understand how objects are serialized and what kind of objects can be serialized (§19.6). F To implement the Serializable interface to make objects serializable (§19.6.1). F To serialize arrays (§19.6.2). F To read and write the same file using the RandomAccessFile class (§19.7).

4 How is I/O Handled in Java? F A File object encapsulates –properties of a file or a path –Does not contain the methods for reading/writing data from/to a file – In order to perform I/O, you need to create objects using appropriate Java I/O classes. Formatter output = new Formatter("temp.txt"); output.format("%s", "Java 101"); output.close(); Scanner input = new Scanner(new File("temp.txt")); System.out.println(input.nextLine());

5 Text File vs. Binary File F text file consists of a sequence of characters F binary file consists of a sequence of bits F decimal integer 199 –is stored as the sequence of three characters: –'1', '9', '9' in a text file –same integer is stored as a byte-type value C7 in a binary file –decimal 199 equals to hex C7.

6 Binary I/O F Text I/O requires encoding and decoding F JVM converts a Unicode to a file specific encoding – When writing a character F Coverts a file specific encoding to a Unicode –when reading a character F Binary I/O does not require conversions –When you write a byte to a file –original byte is copied into the file –When you read a byte from a file –the exact byte in the file is returned

7 Binary I/O Classes

8 The value returned is a byte as an int type. InputStream

9 The value is a byte as an int type. OutputStream

10 FileInputStream/FileOutputStream F FileInputStream/FileOutputStream – –associates a binary input/output stream with an external file F All the methods in FileInputStream/FileOuptputStream – are inherited from its superclasses

11 FileInputStream F Construct a FileInputStream – u use the following constructors: public FileInputStream (String filename) public FileInputStream (File file) F java.io.FileNotFoundException –Attempt to create a FileInputStream with a nonexistent file

12 FileOutputStream F Construct a FileOutputStream – –use the following constructors: public FileOutputStream(String filename) public FileOutputStream(File file) public FileOutputStream(String filename, boolean append) public FileOutputStream(File file, boolean append) F If the file does not exist – –a new file would be created F If the file already exists –To delete the current contents in the file u Use the first two constructors –To retain the current content and append new data into the file u use the last two constructors by passing true to the append parameter TestFileStream Run

13 FilterInputStream/FilterOutputStream

14 F Filter streams – –filter bytes for some purpose –basic byte input stream – u provides a read method that can only be used for reading bytes –read integers, doubles, or strings u need a filter class to wrap the byte input stream –Using a filter class u enables you to read – – integers, –doubles, –Strings instead of bytes and characters u FilterInputStream and FilterOutputStream – –are the base classes for filtering data –When you need to process primitive numeric types, use DataInputStream and DataOutputStream to filter bytes

15 DataInputStream/DataOutputStream F DataInputStream – –reads bytes from the stream and converts them into appropriate primitive type values or strings F DataOutputStream –Converts primitive type values or strings into bytes and output the bytes to the stream

16 DataInputStream F DataInputStream – –extends FilterInputStream and implements the DataInput interface

17 DataOutputStream F DataOutputStream – –extends FilterOutputStream and implements the DataOutput interface

18 Characters and Strings in Binary I/O F A Unicode consists of two bytes F writeChar (char c) method –writes the Unicode of character c to the output F writeChars(String s) method –writes the Unicode for each character in the string s to the output F Why UTF-8? What is UTF-8? –Coding scheme that allows systems to operate with both ASCII and Unicode efficiently –Most operating systems use ASCII –Java uses Unicode –ASCII character set is a subset of the Unicode character set –Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character –UTF-8 is an alternative scheme that stores a character using 1, 2, or 3 bytes –ASCII values (less than 0x7F) are coded in one byte –Unicode values less than 0x7FF are coded in two bytes –Other Unicode values are coded in three bytes

19 Using DataInputStream/DataOutputStream F Data streams – –used as wrappers on existing input and output streams to filter data in the original stream –Created using the following constructors: public DataInputStream (InputStream instream) public DataOutputStream (OutputStream outstream) F statements given below create data streams – first statement creates an input stream for file in.dat – second statement creates an output stream for file out.dat DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat")); TestDataStream Run

20 Checking End of File TIP: –If you keep reading data at the end of a stream u an EOFException would occur –So how do you check the end of a file? u use input.available() to check it u input.available() == 0 indicates that it is the end of a file Order and Format CAUTION: –You have to read the data in the same order and same format in which they are stored –since names are written in UTF-8 using writeUTF, you must read names using readUTF

21 BufferedInputStream/BufferedOutputStream Using buffers to speed up I/O BufferedInputStream/BufferedOutputStream –does not contain new methods –All the methods BufferedInputStream/BufferedOutputStream are inherited from the InputStream/OutputStream classes

22 Constructing BufferedInputStream/BufferedOutputStream // Create a BufferedInputStream public BufferedInputStream (InputStream in) public BufferedInputStream (InputStream in, int bufferSize) // Create a BufferedOutputStream public BufferedOutputStream(OutputStream out) public BufferedOutputStream(OutputStreamr out, int bufferSize)

23 Copy File – Develop a program that copies files – user needs to provide - u source file u target file u as command-line arguments using the following command: java Copy source target – Program copies a source file to a target file – Displays the number of bytes in the file – If the source does not exist u tell the user the file is not found – If the target file already exists u tell the user the file already exists Copy Run

24 Object I/O F DataInputStream/DataOutputStream – –enables you to perform I/O for primitive type values and strings F ObjectInputStream/ObjectOutputStream – –enables you to perform I/O for objects in addition for primitive type values and strings

25 ObjectInputStream ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants

26 ObjectOutputStream ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.

27 Using Object Streams F You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors: // Create an ObjectInputStream public ObjectInputStream(InputStream in) // Create an ObjectOutputStream public ObjectOutputStream(OutputStream out) TestObjectOutputStream Run TestObjectInputStream Run

28 Serializable Interface F Not all objects can be written to an output stream F Serializable – – Objects that can be written to an object stream is said to be serializable –object is an instance of the java.io.Serializable interface –So the class of a serializable object must implement Serializable F 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 F Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays

29 transient Keyword F If an object is an instance of Serializable, F but it contains non-serializable instance data fields F Can the object be serialized? –Answer is – u NO. –For the object to be serialized, you can use the transient keyword to mark these data fields to tell the JVM to ignore these fields when writing the object to an object stream

30 transient Keyword F Consider the following class: public class Foo implements java.io.Serializable { private int v1; private static double v2; private transient A v3 = new A(); } class A { } // A is not serializable F When an object of the Foo class is serialized –only variable v1 is serialized –Variable v2 is not serialized – u because it is a static variable –Variable v3 is not serialized – u because it is marked transient –If v3 were not marked transient – u java.io.NotSerializableException would occur

31 Serializing Arrays F An array is serializable – –if all its elements are serializable F So an entire array can be saved – –using writeObject into a file –later restored using readObject –store an array of – u five int values u three strings u two JButton objects –reads them back to display on the console TestObjectStreamForArray Run

32 Random Access Files F streams used so far are known as – –read-only or write-only streams F External files of these streams are – –sequential files –cannot be updated without creating a new file F It is often necessary – – modify files –insert new records into files F Java provides – –RandomAccessFile class u Allow a file to be read from and write to at random locations

33 RandomAccessFile

34 File Pointer F random access file consists of –a sequence of bytes –a special marker called file pointer u positioned at one of these bytes –A read or write operation takes place at the location of the file pointer –When a file is opened u file pointer sets at the beginning of the file –When you read or write data to the file u file pointer moves forward to the next data u if you read an int value using readInt() –JVM reads four bytes from the file pointer and now the file pointer is four bytes ahead of the previous location.

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

36 RandomAccessFile Methods 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

37 RandomAccessFile Methods 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.

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

39 A Short Example on RandomAccessFile Run TestRandomAccessFile

40 Address Book F use RandomAccessFile to – –Create a useful project for storing and viewing an address book –user interface of the program is shown – Add button – u stores a new address to the end of the file – First, Next, Previous, and Last buttons – u retrieve the first, next, previous, and last addresses from the file, respectively

41 Fixed Length String I/O F Random access files – –are often used to process files of records –fixed-length records are used in random access files u so that a record can be located easily F A record consists of –a fixed number of fields F A field can be –a string or a primitive data type F A string in a fixed-length record has a maximum size F If a string is smaller than the maximum size – rest of the string is padded with blanks. FixedLengthStringIO

42 Address Implementation F Rest of the work can be summarized in the following steps: – Create the user interface. – Add a record to the file. – Read a record from the file. –Write the code to implement the button actions Run AddressBook