Java I/O. Università di Modena e Reggio Emilia Prof. Nicola Bicocchi

Similar documents
INPUT AND OUTPUT STREAMS

Programming in Java

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

What is an I/O Stream?

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

Simple Java I/O. Streams

CS 1302 Ch 19, Binary I/O

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

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

D06 PROGRAMMING with JAVA

JAVA - FILES AND I/O

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

All rights reserved. Copyright in this document is owned by Sun Microsystems, Inc.

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

Input / Output Framework java.io Framework

Files and Streams. Writeappropriatecodetoread,writeandupdatefilesusingFileInputStream, FileOutputStream and RandomAccessFile objects.

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

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Stream Classes and File I/O

Files and input/output streams

WRITING DATA TO A BINARY FILE

CS 193A. Data files and storage

FILE I/O IN JAVA. Prof. Chris Jermaine Prof. Scott Rixner

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

1 of 1 24/05/ :23 AM

ZEMRIS

Java Fundamental Classes Reference

Building a Multi-Threaded Web Server

AVRO - SERIALIZATION

Introduction to Java I/O

Entrada/Salida basada en

Chapter 2: Elements of Java

5 HDFS - Hadoop Distributed System

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

TP N 10 : Gestion des fichiers Langage JAVA

Decorator Pattern [GoF]

B.Sc (Honours) - Software Development

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

Creating a Simple, Multithreaded Chat System with Java

CS506 Web Design and Development Solved Online Quiz No. 01

Object-Oriented Programming in Java

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

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

Introduction to Java

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

13 File Output and Input

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

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

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

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

Java from a C perspective. Plan

Event-Driven Programming

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

Lesson: All About Sockets

Using Files as Input/Output in Java 5.0 Applications

System Calls and Standard I/O

Programming Languages CIS 443

Illustration 1: Diagram of program function and data flow

CSE 8B Midterm Fall 2015

Division of Informatics, University of Edinburgh

File System. /boot /system /recovery /data /cache /misc. /sdcard /sd-ext. Also Below are the for SD Card Fie System Partitions.

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

Mail User Agent Project

Communicating with a Barco projector over network. Technical note

1. Writing Simple Classes:

Quick Introduction to Java

This example illustrates how to copy contents from one file to another file. This topic is related to the I/O (input/output) of

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

Continuous Integration Part 2

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

Java Interview Questions and Answers

Chapter 3. Input and output. 3.1 The System class

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

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

csce4313 Programming Languages Scanner (pass/fail)

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

Java Network. Slides prepared by : Farzana Rahman

Variables, Constants, and Data Types

Install Java Development Kit (JDK) 1.8

Java CPD (I) Frans Coenen Department of Computer Science

filename := Filename named: 'c:\basedir\file.ext'. filename := 'c:\basedir\file.ext' asfilename.

Member Functions of the istream Class

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

Storing Measurement Data

CS 121 Intro to Programming:Java - Lecture 11 Announcements

ProfBuilder: A Package for Rapidly Building Java Execution Profilers Brian F. Cooper, Han B. Lee, and Benjamin G. Zorn

Unit 6. Loop statements

AWS Encryption SDK. Developer Guide

Different types of resources are specified by their scheme, each different pattern is implemented by a specific protocol:

Character Translation Methods

Lab 4: Socket Programming: netcat part

ECE 122. Engineering Problem Solving with Java

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

Eryq (Erik Dorfman) Zeegee Software Inc. A Crash Course in Java 1

! "# $%&'( ) * ).) "%&' 1* ( %&' ! "%&'2 (! ""$ 1! ""3($

CISC 181 Project 3 Designing Classes for Bank Accounts

Introduction to Java. CS 3: Computer Programming in Java

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

Software Development. Chapter 7. Outline The Waterfall Model RISKS. Java By Abstraction Chapter 7

C++ Wrapper Library for Firebird Embedded SQL

Transcription:

Java I/O Università di Modena e Reggio Emilia Prof. Nicola Bicocchi (nicola.bicocchi@unimore.it)

Java I/O Stream Buffer File StringTokenizer, StreamTokenizer SerializaAon

Stream All I/O operaaons rely on the abstracaon of STREAM ( bytes flow ) A stream can be: A file on the disk standard input, output, error A network connecaon A data- flow from/to whichever hardware device I/O operaaons work in the same way with ALL kinds of stream

Stream Reader Writer stream of chars (Unicode Chars 16 bit) All characters InputStream OutputStream stream of bytes (8 bit) Binary data, sounds, images package java.io All related excepaons are subclasses of IOExcepAon

Base classes in java.io

java.io.reader

java.io.reader void close() Close the stream. int read() Read a single character: - 1 when end of stream. Block unal char is available, I/ O error, end of stream. int read(char[] cbuf) Read characters into an array. abstract int read(char[] cbuf, int off, int len) Read characters into a poraon of an array. boolean ready() Tell whether this stream is ready to be read. void reset() Reset the stream. long skip(long n) Skip characters.

java.io.writer

java.io.writer close() Close the stream, flushing it first. abstract void flush() Flush the stream. void write(char[] cbuf) Write an array of characters. abstract void write(char[] cbuf, int off, int len) Write a poraon of an array of characters. void write(int c) Write a single character. void write(string str) Write a string. void write(string str, int off, int len) Write a poraon of a string.

java.io.inputstream

java.io.inputstream int available() Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream. void close() Closes this input stream and releases any system resources associated with the stream. abstract int read() Reads the next byte of data from the input stream. int read(byte[] b) Reads some number of bytes from the input stream and stores them into the buffer array b. int read(byte[] b, int off, int len) Reads up to len bytes of data from the input stream into an array of bytes. void reset() ReposiAons this stream to the posiaon at the Ame the mark method was last called on this input stream. long skip(long n) Skips over and discards n bytes of data from this input stream.

java.io.outputstream

java.io.outputstream void close() Closes this output stream and releases any system resources associated with this stream. void flush() Flushes this output stream and forces any buffered output bytes to be wri]en out. void write(byte[] b) Writes b.length bytes from the specified byte array to this output stream. void write(byte[] b, int off, int len) Writes len bytes from the specified byte array starang at offset off to this output stream. abstract void write(int b) Writes the specified byte to this output stream.

System.in and System.out System defines default input and output streams class System { staac InputStream in; staac PrintStream out; // see aaer }

Stream specializaaons Memory (source/desanaaon) Pipe (source/desanaaon) File (source/desanaaon) Buffered (funcaonality) Printed (funcaonality) Interpreted (funcaonality)

Read/Write in memory CharArrayReader CharArrayWriter R/W char or byte from/to array in memory ByteArrayInputStream ByteArrayOutputStream R/W char or byte from/to array in memory StringReader StringWriter R/W chars from/to String

Read/Write of pipes Pipes are used in inter- process communicaaon PipedReader PipedWriter R/W chars from pipe PipedInputStream PipedOutputStream R/W bytes from pipe

Read/Write of files FileReader FileWriter R/W char from file FileInputStream FileOutputStream R/W byte from file File handles filename and pathname

Buffered Streams BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter Examples: BufferedInputStream(InputStream i) BufferedInputStream(InputStream i, int size)

Printed Streams PrintStream(OutputStream o) print() println() for primiave types and String Do not throw IOExcepAon, but it sets a bit, to be checked with method checkerror() System defines out and err class System { sta,c PrintStream out, err; }

Interpreted Streams Translates primiave types in standard format (UTF- 8) on file DataInputStream(InputStream i) readbyte(), readchar(), readdouble(), readfloat(), readint(), readlong(), readshort() DataOutputStream(OutputStream o) writebyte(), writechar(), writedouble(), writefloat(), writeint(), writelong(), writeshort()

File abstract pathname directory, file, file separator absolute, relaave convert abstract pathname <- - > string methods: create() delete() exists(), mkdir(), getname() getabsolutepath(), getpath(), getparent(), isfile(), isdirectory(), ishidden(), length(), listfiles(), renameto()

Example: text file copy import java.io.*; public class Copy { public staac void main(string[] args) throws IOExcepAon { File inputfile = new File("farrago.txt"); File outputfile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read())!= - 1) out.write(c); in.close(); out.close(); }}

Conversion byte <- - > char InputStreamReader byte - - > char OutputStreamWriter char - - > byte

Tokenizers StringTokenizer Works on String set of delimiters (blank,,, \t, \n, \r, \f ) Blank is the default delimiter Divides a String in tokens (separated by delimiters), returning the token hasmoretokens(), nexttoken() Does not disanguish idenafiers, numbers, comments, quoted strings

Tokenizers StreamTokenizer Works on Stream (Reader) More sophisacated, recognizes idenafiers, comments, quoted string, numbers Use symbol table and flag nexttoken(), TT_EOF if at the end

Deep/Shallow Copy

Deep/Shallow Copy

Deep/Shallow Copy

SerializaAon Read / write of an object imply: read/write a]ributes (and opaonally the type) of the object Correctly separaang different elements When reading, create an object and set all a]ributes values These operaaons (serializaaon) are automated by ObjectInputStream ObjectOutputStream

SerializaAon Methods to read/write objects are: void writeobject(object) Object readobject() ONLY objects implemenang interface Serializable can be serialized This interface is empty. Just used to avoid serializaaon of objects, without permission of the class developer

SerializaAon, deep copy An ObjectOutputStream saves automaacally all objects referred by its a]ributes objects serialized are numbered in the stream references are saved like ordering numbers in the stream If I save 2 objects poinang to a third one, this is saved just once Before saving an object, ObjectOutputStream checks if it has not been already saved Otherwise it saves just the reference (as a number)

SerializaAon, type recovery When reading, an object is created... but which is its type? Down casang to the exact type is useful only to send specific messages A viable soluaon could be down casang to a common ancestor