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



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

CS 1302 Ch 19, Binary I/O

INPUT AND OUTPUT STREAMS

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

AVRO - SERIALIZATION

D06 PROGRAMMING with JAVA

Programming in Java

Creating a Simple, Multithreaded Chat System with Java

WRITING DATA TO A BINARY FILE

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

CS506 Web Design and Development Solved Online Quiz No. 01

13 File Output and Input

Input / Output Framework java.io Framework

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

Course Intro Instructor Intro Java Intro, Continued

Building a Multi-Threaded Web Server

JAVA - FILES AND I/O

Files and input/output streams

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

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

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Chapter 2: Elements of Java

TP N 10 : Gestion des fichiers Langage JAVA

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

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

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

Stream Classes and File I/O

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

Continuous Integration Part 2

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

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

Event-Driven Programming

Object-Oriented Programming in Java

Using Files as Input/Output in Java 5.0 Applications

Lesson: All About Sockets

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

Java from a C perspective. Plan

Objectives. Streams and File I/O. Objectives, cont. Outline. I/O Overview. Streams

AP Computer Science Java Subset

JAVA Program For Processing SMS Messages

Division of Informatics, University of Edinburgh

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

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

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

Network/Socket Programming in Java. Rajkumar Buyya

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

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

Using NetBeans IDE to Build Quick UI s Ray Hylock, GISo Tutorial 3/8/2011

Mail User Agent Project

Explain the relationship between a class and an object. Which is general and which is specific?

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

An Overview of Java. overview-1

The C Programming Language course syllabus associate level

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Java Interview Questions and Answers

Basic Programming and PC Skills: Basic Programming and PC Skills:

Crash Course in Java

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

Java Fundamental Classes Reference

Chapter 2 Introduction to Java programming

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

Introduction to Java

1. Writing Simple Classes:

Reading Input From A File

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

CS 106 Introduction to Computer Science I

1 of 1 24/05/ :23 AM

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

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

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Unit Testing & JUnit

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

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Communicating with a Barco projector over network. Technical note

The Interface Concept

The programming language C. sws1 1

Lecture 7: Class design for security

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

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

Java Network. Slides prepared by : Farzana Rahman

Package hive. January 10, 2011

Computer Programming I

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

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

Text file I/O and simple GUI dialogues

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

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

Lecture 5: Java Fundamentals III

Serialization in Java (Binary and XML)

String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivepacket.getaddress(); int port = receivepacket.

Transcription:

File I/O - Chapter 10 A Java stream is a sequence of bytes. An InputStream can read from a file the console (System.in) a network socket an array of bytes in memory a StringBuffer a pipe, which is an OutputStream An OutputStream can write to a file, etc. 1 Many Stream Classes Java has many different stream classes. The classes differ in the methods they provide for converting "regular" Java values to/from sequences of bytes. The classes also differ in how they are constructed. For example, can you specify the name of a file as a String when constructing a particular stream class. 2 Text Files vs Binary Files text files contain "text", usually in ASCII everything else is a binary file 1234 vs "1234" byte 0 byte 1 byte 2 byte 3 00000000 00000000 00000100 11010010 0 0 4 210 49 50 51 52 3 1

import java.io.*; Writing Text Files class HelloFile throws java.io.ioexception PrintWriter out = new PrintWriter(new FileWriter("hello.txt")); out.println("hello, file system!"); out.close(); String, Object, or primitive type char byte PrintWriter FileWriter File stream stream 4 import tio.*; Reading Text Files class FileReadInput ReadInput in = new ReadInput("sample.txt"); int x = in.readint(); double y = in.readdouble(); String s = in.readword(); System.out.println("x = "+x); System.out.println("y = "+y); System.out.println("s = "+s); 5 EOF with hasmoreelements() //WordCount.java - count the words in a file import tio.*; class WordCount ReadInput in = new ReadInput("sample.txt"); int count = 0; while (in.hasmoreelements()) String word = in.readword(); count++; System.out.println("There were "+count+" words."); 6 2

Reading Text Files without tio import java.io.*; class HelloFileRead2 throws IOException BufferedReader in = new BufferedReader( new FileReader("hello.txt")); System.out.println(in.readLine()); String char byte BufferedReader FileReader File stream stream 7 Formatting Text Output C uses printf( ) C++ uses streams cout << setw(10) << i<< j << k For tio we followed the C++ model 8 //FormattedOutput.java - demo of formatted text output import tio.*; class FormattedOutput throws java.io.ioexception int x = 1, y = 22; double z = 4.5678E-20; FormattedWriter out = new FormattedWriter(System.out); out.setwidth(10); out.setdigits(2); out.printf("col1"); out.printf("col2"); out.printfln("col3"); out.printf(x); out.printf(y); out.printfln(z); 9 3

package tio; import java.io.*; import java.text.*; public class FormattedWriter extends PrintWriter // constants for specifying justification public static final int LEFT = 1; public static final int RIGHT = 2; public FormattedWriter(OutputStream os) super(os, true); // make default auto-flushing public FormattedWriter(FileWriter writer) super(writer, true); public FormattedWriter(String filename) throws java.io.ioexception this(new FileWriter(filename)); 10 public void setwidth(int width) if (width < 0) this.width = 0; else if (width > MAX_WIDTH) this.width = MAX_WIDTH; else this.width = width; public void setdigits(int places) decimalplaces = places; form.setmaximumfractiondigits(decimalplaces); 11 public void setjustify(int leftorright) if (leftorright!= LEFT && leftorright!= RIGHT) throw new IllegalArgumentException( "use FormattedWriter.LEFT or" + " FormattedWriter.RIGHT"); justify = leftorright; public void setpadchar(char pad) if (pad == ) padding = spaces; else if (pad == 0 ) padding = zeros; else padding = buildpadding(max_width, pad); 12 4

public void printf(string s) if (s.length() >= width) super.print(s); else if (justify == LEFT) super.print(s + padding.substring(0, width - s.length())); else super.print( padding.substring(0, width - s.length()) + s); public void printf(boolean value) printf(string.valueof(value));... 13 Binary I/O DataInputStream/DataOutputStream readboolean(), readint(), readfloat(),, readutf() NOT the same as readint() from tio which reads TEXT and parses it into an int. 14 import java.io.*; class BinIOTest throws IOException DataOutputStream out = new DataOutputStream( new FileOutputStream("test.bin")); double x = 1.0; int count = 10; out.writeint(count); for (int i = 0; i < count; i++) out.writedouble(x); x = x / 3.0; out.close(); 15 5

DataInputStream in = new DataInputStream( new FileInputStream("test.bin")); count = in.readint(); for (int i = 0; i < count; i++) System.out.println(in.readDouble()); 16 import java.io.*; class ObjectIO throws Exception int[] somearray = 1,2,3; Stack stack = new Stack(); stack.push(new Integer(1)); stack.push("two"); stack.push(somearray); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("outfile")); out.writeobject(stack); out.close(); 17 stack = null; somearray = null; ObjectInputStream in = new ObjectInputStream(new FileInputStream("outfile")); stack = (Stack)(in.readObject()); somearray = (int[])stack.pop(); System.out.println(someArray[1]); System.out.println(stack.pop()); System.out.println(stack.pop()); 18 6

//Stack.java - a generic stack class Stack implements java.io.serializable Object top()... void push(object value)... Object pop()... boolean empty() return top == null; private ListElement top = null; 19 //ListElement.java - a generic list element class ListElement implements java.io.serializable ListElement(Object value) data = value; ListElement next; Object data; 20 EOF input method returns a special value input method throws an exception special method used to check for more input 21 7

EOF Summary Class tio.readinput java.io.datainputstream java.io.bufferedreader Method all readline() readchar() readprimitive() readline() read() readline() read() EOF detected by hasmoreelements() returns null returns -1 EOFException returns null returns -1 returns null returns -1 22 Another Example of ObjectIO The following example reinforces that an ObjectOutputStream can handle recursive data structures. 23 import java.io.*; import java.util.vector; class Graph implements Serializable Node root; void print() root.print(); root.reset(); 24 8

class Node implements Serializable int value; boolean visited; Vector children = new Vector(); Node(int v) value = v; void print() if (visited) return; System.out.print(value + ":"); for (int i = 0; i < children.size(); i++) System.out.print( ((Node)(children.elementAt(i))).value + " "); System.out.println(); visited = true; for (int i = 0; i < children.size(); i++) ((Node)(children.elementAt(i))).print(); 25 void reset() if (!visited) return; visited = false; for (int i = 0; i < children.size(); i++) ((Node)(children.elementAt(i))).reset(); 26 class GraphTest throws IOException, ClassNotFoundException Graph thegraph = new Graph(); Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(3); Node node4 = new Node(4); thegraph.root = node1; node1.children.add(node2); node1.children.add(node3); node2.children.add(node4); node3.children.add(node4); node4.children.add(node1); thegraph.print(); 27 9

ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("outfile")); out.writeobject(thegraph); out.close(); 28 class GraphRestore throws IOException, ClassNotFoundException Graph thegraph; ObjectInputStream in = new ObjectInputStream(new FileInputStream("outfile")); thegraph = (Graph)(in.readObject()); System.out.println("resurrected"); thegraph.print(); 29 More about Serializable So what can't be serialized automatically? There are many things. One example is an open file stream. In general, anything that involves state that is outside of the Java Virtual Machine, such as the file system state for an open file stream. 30 10

Special Handling of Objects If you want to serialize an object that requires special handling, have the class implement private void writeobject(java.io.objectoutputstream out) throws IOException; and private void readobject(java.io.objectinputstream in) throws IOException, ClassNotFoundException; 31 class Graph implements Serializable Node root; void print() root.print(); root.reset(); private void writeobject(objectoutputstream out) throws IOException System.out.println("Writing"); out.defaultwriteobject(); private void readobject(objectinputstream in) throws IOException, ClassNotFoundException System.out.println("reading"); in.defaultreadobject(); 32 11