Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.



Similar documents
D06 PROGRAMMING with JAVA

INPUT AND OUTPUT STREAMS

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

Programming in Java

CS 1302 Ch 19, Binary I/O

What is an I/O Stream?

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

Capitolo 14: Flussi. Capitolo 14. Flussi Apogeo srl Horstmann-Concetti di informatica e fondamenti di Java 2

Files and input/output streams

JAVA - FILES AND I/O

D06 PROGRAMMING with JAVA

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

WRITING DATA TO A BINARY FILE

13 File Output and Input

Using Files as Input/Output in Java 5.0 Applications

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

AVRO - SERIALIZATION

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Creating a Simple, Multithreaded Chat System with Java

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

public static void main(string[] args) { System.out.println("hello, world"); } }

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Introduction to Java

AP Computer Science Static Methods, Strings, User Input

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Chapter 2: Elements of Java

Introduction to Programming

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Chapter 2 Introduction to Java programming

Object-Oriented Programming in Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Input / Output Framework java.io Framework

Building a Multi-Threaded Web Server

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

AP Computer Science Java Mr. Clausen Program 9A, 9B

Stream Classes and File I/O

AP Computer Science Java Subset

Today s Outline. Computer Communications. Java Communications uses Streams. Wrapping Streams. Stream Conventions 2/13/2016 CSE 132

Sample CSE8A midterm Multiple Choice (circle one)

Chapter 3. Input and output. 3.1 The System class

Event-Driven Programming

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Readings and References. Topic #10: Java Input / Output. "Streams" are the basic I/O objects. Input & Output. Streams. The stream model A-1.

Principles of Software Construction: Objects, Design, and Concurrency. Design Case Study: Stream I/O Some answers. Charlie Garrod Jonathan Aldrich

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

CS506 Web Design and Development Solved Online Quiz No. 01

Decorator Pattern [GoF]

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

More on Objects and Classes

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Java Interview Questions and Answers

Part I. Multiple Choice Questions (2 points each):

J a v a Quiz (Unit 3, Test 0 Practice)

Communicating with a Barco projector over network. Technical note

Topic 11 Scanner object, conditional execution

1 of 1 24/05/ :23 AM

Continuous Integration Part 2

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

The Interface Concept

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Lesson: All About Sockets

AWS Encryption SDK. Developer Guide

JAVA ARRAY EXAMPLE PDF

D06 PROGRAMMING with JAVA

Java from a C perspective. Plan

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. AVRO Tutorial

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

Application Development with TCP/IP. Brian S. Mitchell Drexel University

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Zebra and MapReduce. Table of contents. 1 Overview Hadoop MapReduce APIs Zebra MapReduce APIs Zebra MapReduce Examples...

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

COSC 6397 Big Data Analytics. Distributed File Systems (II) Edgar Gabriel Spring HDFS Basics

Arrays in Java. Working with Arrays

Course Intro Instructor Intro Java Intro, Continued

CS 111 Classes I 1. Software Organization View to this point:

Install Java Development Kit (JDK) 1.8

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Building Java Programs

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Introduction to Java. CS 3: Computer Programming in Java

Serialization in Java (Binary and XML)

Building Java Programs

Week 1: Review of Java Programming Basics

CSE 8B Midterm Fall 2015

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

AP Computer Science File Input with Scanner

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

6.1. Example: A Tip Calculator 6-1

Transcription:

Chapter 20 Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

20.1 Readers, Writers, and Streams Two ways to store data: Text format: human-readable form, as a sequence of characters E.g. Integer 12,345 stored as characters '1' '2' '3' '4' '5' More convenient for humans: easier to produce input and to check output Readers and writers handle data in text form Binary format: data items are represented in bytes E.g. Integer 12,345 stored as sequence of four bytes 0 0 48 57 More compact and more efficient Streams handle binary data Copyright 2014 by John Wiley & Sons. All rights reserved. Page 2

Java Classes for Input and Output Copyright 2014 by John Wiley & Sons. All rights reserved. Page 3

Text Data Reader and Writer and their subclasses were designed to process text input and output PrintWriter was used in Chapter 7 Scanner class is more convenient than Reader class By default, these classes use the character encoding of the computer executing the program OK, when only exchanging data with users from same country Otherwise, good idea to use UTF-8 encoding: Scanner in = new Scanner(input, "UTF-8"); // Input can be a File or InputStream PrintWriter out = new PrintWriter(output, "UTF-8"); // Output can be a File or OutputStream Copyright 2014 by John Wiley & Sons. All rights reserved. Page 4

20.2 Binary Input and Output Use InputStream and OutputStream and their subclasses to process binary input and output To read: FileInputStream inputstream = new FileInputStream("input.bin"); To write: FileOutputStream outputstream = new FileOutputStream("output.bin"); System.out is a PrintStream object Copyright 2014 by John Wiley & Sons. All rights reserved. Page 5

Binary Input Use read method of InputStream class to read a single byte returns the next byte as an int between 0 and 255 or, the integer -1 at end of file InputStream in =...; int next = in.read(); if (next!= -1) { Process next // a value between 0 and 255 } Copyright 2014 by John Wiley & Sons. All rights reserved. Page 6

Binary Output Use write method of OutputStream class to write a single byte: OutputStream out =...; int value=...; // should be between 0 and 255 out.write(value); When finished writing to the file, close it: out.close(); Copyright 2014 by John Wiley & Sons. All rights reserved. Page 7

20.3 Random Access Sequential access: process file one byte at a time Random access: access file at arbitrary locations Only disk files support random access System.in and System.out do not Each disk file has a special file pointer position Read or write at pointer position Copyright 2014 by John Wiley & Sons. All rights reserved. Page 8

RandomAccessFile Class Open a file with open mode: Reading only ("r") Reading and writing ("rw") RandomAccessFile f = new RandomAcessFile("bank.dat","rw"); To move the file pointer to a specific byte: f.seek(position); To get the current position of the file pointer: long position = f.getfilepointer(); // of type "long" because files can be very large To find the number of bytes in a file: long filelength = f.length(); Copyright 2014 by John Wiley & Sons. All rights reserved. Page 9

Bank Account Program (1) Use a random access file to store a set of bank accounts Program lets you pick an account and deposit money into it To manipulate a data set in a file, pay special attention to data formatting Suppose we store the data as text Say account 1001 has a balance of $900, and account 1015 has a balance of 0: Want to deposit $100 into account 1001: Writing out the new value: Copyright 2014 by John Wiley & Sons. All rights reserved. Page 10

Bank Account Program (2) Better way to manipulate a data set in a file: Give each value a fixed size that is sufficiently large Every record has the same size Easy to skip quickly to a given record To store numbers, it is easier to store them in binary format Copyright 2014 by John Wiley & Sons. All rights reserved. Page 11

Bank Account Program (3) RandomAccessFile class stores binary data readint and writeint methods read/write integers as four-byte quantities readdouble and writedouble methods use eight-byte quantities To find out how many bank accounts are in the file: public int size() throws IOException { return (int) (file.length() / RECORD_SIZE); // RECORD_SIZE is 12 bytes: // 4 bytes for account number plus // 8 bytes for balance } Copyright 2014 by John Wiley & Sons. All rights reserved. Page 12

Bank Account Program (4) To read the n th account in the file: public BankAccount read(int n) throws IOException { file.seek(n * RECORD_SIZE); int accountnumber = file.readint(); double balance = file.readdouble(); return new BankAccount(accountNumber, balance); } Copyright 2014 by John Wiley & Sons. All rights reserved. Page 13

Bank Account Program (5) To write the n th account in the file: public void write(int n, BankAccount account) throws IOException { file.seek(n * RECORD_SIZE); file.writeint(account.getaccountnumber()); file.writedouble(account.getbalance()); } Copyright 2014 by John Wiley & Sons. All rights reserved. Page 14

BankSimulator.java 1 import java.io.ioexception; 2 import java.util.scanner; 3 4 /** 5 This program demonstrates random access. You can access existing 6 accounts and deposit money, or create new accounts. The 7 accounts are saved in a random access file. 8 */ 9 public class BankSimulator 10 { 11 public static void main(string[] args) throws IOException 12 { 13 Scanner in = new Scanner(System.in); 14 BankData data = new BankData(); 15 try 16 { 17 data.open("bank.dat"); 18 Continued Copyright 2014 by John Wiley & Sons. All rights reserved. Page 15

BankSimulator.java (cont.) 19 boolean done = false; 20 while (!done) 21 { 22 System.out.print("Account number: "); 23 int accountnumber = in.nextint(); 24 System.out.print("Amount to deposit: "); 25 double amount = in.nextdouble(); 26 27 int position = data.find(accountnumber); 28 BankAccount account; 29 if (position >= 0) 30 { 31 account = data.read(position); 32 account.deposit(amount); 33 System.out.println("New balance: " + account.getbalance()); 34 } Continued Copyright 2014 by John Wiley & Sons. All rights reserved. Page 16

BankSimulator.java (cont.) 35 else // Add account 36 { 37 account = new BankAccount(accountNumber, amount); 38 position = data.size(); 39 System.out.println("Adding new account."); 40 } 41 data.write(position, account); 42 43 System.out.print("Done? (Y/N) "); 44 String input = in.next(); 45 if (input.equalsignorecase("y")) done = true; 46 } 47 } 48 finally 49 { 50 data.close(); 51 } 52 } 53 } Copyright 2014 by John Wiley & Sons. All rights reserved. Page 17

BankData.java 1 import java.io.ioexception; 2 import java.io.randomaccessfile; 3 4 /** 5 This class is a conduit to a random access file 6 containing bank account records. 7 */ 8 public class BankData 9 { 10 private RandomAccessFile file; 11 12 public static final int INT_SIZE = 4; 13 public static final int DOUBLE_SIZE = 8; 14 public static final int RECORD_SIZE = INT_SIZE + DOUBLE_SIZE; 15 16 /** 17 Constructs a BankData object that is not associated with a file. 18 */ 19 public BankData() 20 { 21 file = null; 22 } Continued 23 Copyright 2014 by John Wiley & Sons. All rights reserved. Page 18

BankData.java (cont.) 24 /** 25 Opens the data file. 26 @param filename the name of the file containing bank 27 account information 28 */ 29 public void open(string filename) 30 throws IOException 31 { 32 if (file!= null) { file.close(); } 33 file = new RandomAccessFile(filename, "rw"); 34 } 35 36 /** 37 Gets the number of accounts in the file. 38 @return the number of accounts 39 */ 40 public int size() 41 throws IOException 42 { 43 return (int) (file.length() / RECORD_SIZE); 44 } 45 Continued Copyright 2014 by John Wiley & Sons. All rights reserved. Page 19

BankData.java (cont.) 46 /** 47 Closes the data file. 48 */ 49 public void close() 50 throws IOException 51 { 52 if (file!= null) { file.close(); } 53 file = null; 54 } 55 56 /** 57 Reads a bank account record. 58 @param n the index of the account in the data file 59 @return a bank account object initialized with the file data 60 */ 61 public BankAccount read(int n) 62 throws IOException 63 { 64 file.seek(n * RECORD_SIZE); 65 int accountnumber = file.readint(); 66 double balance = file.readdouble(); 67 return new BankAccount(accountNumber, balance); 68 } 69 Continued Page 20

BankData.java (cont.) 70 /** 71 Finds the position of a bank account with a given number 72 @param accountnumber the number to find 73 @return the position of the account with the given number, 74 or -1 if there is no such account 75 */ 76 public int find(int accountnumber) 77 throws IOException 78 { 79 for (int i = 0; i < size(); i++) 80 { 81 file.seek(i * RECORD_SIZE); 82 int a = file.readint(); 83 if (a == accountnumber) {return i; } 84 // Found a match 85 } 86 return -1; // No match in the entire file 87 } 88 Continued Copyright 2014 by John Wiley & Sons. All rights reserved. Page 21

BankData.java (cont.) 89 /** 90 Writes a bank account record to the data file 91 @param n the index of the account in the data file 92 @param account the account to write 93 */ 94 public void write(int n, BankAccount account) 95 throws IOException 96 { 97 file.seek(n * RECORD_SIZE); 98 file.writeint(account.getaccountnumber()); 99 file.writedouble(account.getbalance()); 100 } 101 } Continued Copyright 2014 by John Wiley & Sons. All rights reserved. Page 22

BankData.java (cont.) Program Run: Account number: 1001 Amount to deposit: 100 Adding new account. Done? (Y/N) N Account number: 1018 Amount to deposit: 200 Adding new account. Done? (Y/N) N Account number: 1001 Amount to deposit: 1000 New balance: 1100.0 Done? (Y/N) Y Copyright 2014 by John Wiley & Sons. All rights reserved. Page 23

20.4 Object Streams ObjectOutputStream class can save entire objects to disk ObjectInputStream class can read them back in Use streams, not writers because objects are saved in binary format Copyright 2014 by John Wiley & Sons. All rights reserved. Page 24

Writing an Object to File The object output stream saves all instance variables: BankAccount b =...; ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("bank.dat")); out.writeobject(b); Copyright 2011 by John Wiley & Sons. All rights reserved. Page 25

Reading an Object From File readobject method returns an Object reference Need to remember the types of the objects that you saved and use a cast: ObjectInputStream in = new ObjectInputStream( new FileInputStream("bank.dat")); BankAccount b =(BankAccount) in.readobject(); readobject method can throw ClassNotFoundException Checked exception you must catch or declare it Copyright 2014 by John Wiley & Sons. All rights reserved. Page 26

Write: Write and Read Array List ArrayList<BankAccount> a = new ArrayList<BankAccount>(); // Now add many BankAccount objects into a out.writeobject(a); Read: ArrayList<BankAccount> a = (ArrayList<BankAccount>) in.readobject(); Copyright 2014 by John Wiley & Sons. All rights reserved. Page 27

Serializable Interface Objects that are written to an object stream must belong to a class that implements the Serializable interface: class BankAccount implements Serializable { } Serializable interface has no methods Serialization: Process of saving objects to a stream Each object is assigned a serial number on the stream If the same object is saved twice, only serial number is written out the second time When reading, duplicate serial numbers are restored as references to the same object Copyright 2014 by John Wiley & Sons. All rights reserved. Page 28

Bank.java Continued Copyright 2014 by John Wiley & Sons. All rights reserved. Page 29

Bank.java (cont.) Copyright 2014 by John Wiley & Sons. All rights reserved. Page 30

SerialDemo.java Continued Copyright 2014 by John Wiley & Sons. All rights reserved. Page 31

SerialDemo.java (cont.) Continued Copyright 2014 by John Wiley & Sons. All rights reserved. Page 32

SerialDemo.java (cont.) Copyright 2014 by John Wiley & Sons. All rights reserved. Page 33

Summary: Java Class Hierarchy for Handling Input and Output Streams access sequences of bytes. Readers and writers access sequences of characters. Copyright 2014 by John Wiley & Sons. All rights reserved. Page 34

Summary: Input and Output of Binary Data Use FileInputStream and FileOutputStream classes to read and write binary data from and to disk files. The InputStream.read method returns an integer, either -1 to indicate end of input, or a byte between 0 and 255. The OutputStream.write method writes a single byte. Copyright 2014 by John Wiley & Sons. All rights reserved. Page 35

Summary: Random Access In sequential file access, a file is processed one byte at a time. Random access allows access at arbitrary locations in the file, without first reading the bytes preceding the access location. A file pointer is a position in a random access file. Because files can be very large, the file pointer is of type long. The RandomAccessFile class reads and writes numbers in binary form. Copyright 2014 by John Wiley & Sons. All rights reserved. Page 36

Summary: Object Streams Use object streams to save and restore all instance variables of an object automatically. Objects saved to an object stream must belong to classes that implement the Serializable interface. Copyright 2014 by John Wiley & Sons. All rights reserved. Page 37