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

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

Software 1. Java I/O

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

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

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

תוכנה 1 4 תרגול מס' שימוש במחלקות קיימות: קלט/פלט )IO(

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

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

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

Example: Copying the contents of a file

Exceptions and Working with Files

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

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

CSC 1214: Object-Oriented Programming

CS 251 Intermediate Programming Java I/O Streams

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

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

Darshan Institute of Engineering & Technology for Diploma Studies

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

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

I/O Streams. Object-oriented programming

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

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

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

Objec&ves. Review. Standard Error Streams

CSD Univ. of Crete Fall Files, Streams, Filters

Writing usable APIs in practice

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

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

Chapter 10. IO Streams

Object-Oriented Programming Design. Topic : Streams and Files

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

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

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

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

Java IO and C++ Streams

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

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

PIC 20A Streams and I/O

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

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

Writing usable APIs in practice

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

Introduction to Java

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

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

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

pre-emptive non pre-emptive

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

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

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

1.00 Lecture 30. Sending information to a Java program

IT101. File Input and Output

Java Input/Output. 11 April 2013 OSU CSE 1

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

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

Dining philosophers (cont)

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. Representation of Primitive Java Types. CSE143 Sp

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

C17: I/O Streams and File I/O

10.1 Overview 162 CHAPTER 10 CHARACTER STREAMS

Files and Streams

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Object Oriented Software Design

Object Oriented Software Design

Chapter 8: Files and Security

Lecture 11.1 I/O Streams

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

Algorithms. Produced by. Eamonn de Leastar

ITI Introduction to Computer Science II

1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java

Object-Oriented Programming in the Java language

Programmierpraktikum

Performing input and output operations using a Byte Stream

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine

Index. CalculatorEngine class, 40, 44 CalculatorFrame class, 48 CalculatorInterface class, 45

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

Job Migration. Job Migration

CN208 Introduction to Computer Programming

CPS122 Lecture: Input-Output

Experiment No: Group B_4

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

Chapter 10 Input Output Streams

CS193j, Stanford Handout #26. Files and Streams

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

Software Practice 1 - File I/O

Java Input/Output Streams

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

The Java Series IO, Serialization and Persistence. The Java Series. IO, Serialization and Persistence Raul RAMOS / CERN-IT User Support Slide 1

FILE I/O IN JAVA. Prof. Chris Jermaine

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

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

File Operations in Java. File handling in java enables to read data from and write data to files

Simple Java Input/Output

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax

Remedial Java - io 8/09/16. (remedial) Java. I/O. Anastasia Bezerianos 1

J.73 J.74 THE I/O PACKAGE. Java I/O is defined in terms of streams. Streams are ordered sequences of data that have a source and a destination.

The Decorator Pattern. Design Patterns In Java Bob Tarr

Transcription:

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

The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating files Classes for serializing objects May 29, 2007 2

Online Resources JAVA API Specification: http://java.sun.com/j2se/1.5.0/docs/api/index.html The Java Tutorial (Sun) http://java.sun.com/docs/books/tutorial/essential/io/ May 29, 2007 3

Streams A stream is a sequential flow of data Streams are one-way streets. Input streams are for reading Output streams are for writing File Memory Socket Source Target Input Stream Output Stream read write Program Program May 29, 2007 4

Streams Usage Flow: open a stream while more information Read/write information close the stream All streams are automatically opened when created. May 29, 2007 5

Streams There are two types of streams: Byte streams for reading/writing raw bytes Character streams for reading/writing text Class Name Suffix Convention: Input Output Byte InputStream OutputStream Character Reader Writer May 29, 2007 6

InputStreams ByteArrayInputStream InputStream abstract super-class FileInputStream FilterInputStream ObjectInputStream PipedInputStream SequenceInputStream DataInputStream BufferedInputStream PushbackInputStream - read from data sinks - perform some processing May 29, 2007 7

OutputStreams ByteArrayOutputStream OutputStream abstract super-class FileOutputStream FilterOutputStream ObjectOutputStream PipedOutputStream BufferedOutputStream DataOutputStream PrintStream - write to data sinks - perform some processing May 29, 2007 8

Readers BufferedReader LineNumberReader Reader abstract super-class CharArrayReader FilterReader InputStreamReader PipedReader StringReader PushbackReader FileReader - read from data sinks - perform some processing May 29, 2007 9

Writers Writer abstract super-class BufferedWriter CharArrayWriter FilterWriter OutputStreamWriter PipedWriter PrintWriter FileWriter - write to data sinks - perform some processing StringWriter May 29, 2007 10

Terminal I/O The System class provides references to the standard input, output and error streams: InputStream stdin = System.in; PrintStream stdout = System.out; PrintStream stderr = System.err; May 29, 2007 11

InputStream Example Reading a single byte from the standard input stream: an int with a byte information try { int value = System.in.read();... } catch (IOException e) { }... is thrown in case of an error returns -1 if a normal end of stream has been reached May 29, 2007 12

InputStream Example Another implementation: end-ofstream condition try { int value = System.in.read(); if (value!= -1) { }... byte bvalue = (byte) value; } catch (IOException e) {...} casting May 29, 2007 13

Character Stream Example FileReader in = null; FileWriter out = null; try { in = new FileReader("in.txt"); out = new FileWriter("out.txt"); int c; while ((c = in.read())!= -1) { out.write(c); } } catch (IOException e) { } finally { if (in!= null) in.close(); if (out!= null) out.close(); } May 29, 2007 14

Character Stream Example public static void main(string[] args) { try { FileReader in = new FileReader("in.txt"); FileWriter out = new FileWriter("out.txt"); int c; while ((c = in.read())!= -1) { out.write(c); } in.close(); out.close(); } catch (IOException e) { // Do something } } May 29, 2007 15

Stream Wrappers Some streams wrap others streams and add new features. A wrapper stream accepts another stream in its constructor: DataInputStream din = new DataInputStream(System.in); double d = din.readdouble(); readboolean() readfloat() din DataInputStream System.in InputStream May 29, 2007 16

Stream Wrappers (cont.) Reading a text string from the standard input: try { InputStreamReader in = new InputStreamReader(System.in); BufferedReader bin = new BufferedReader(in); String text = bin.readline();... } catch (IOException e) {...} readline bin BufferedReader in InputStreamReader System.in InputStream May 29, 2007 17

The Scanner Class Breaks its input into tokens using a delimiter pattern (matches whitespace by default) The resulting tokens may then be converted into values try { Scanner s = new Scanner(System.in); int anint = s.nextint(); float afloat = s.nextfloat(); String astring = s.next(); String aline = s.nextline(); } catch ( ) { } May 29, 2007 18

The File Class Represents a file or directory pathname Performs basic file system operations: removes a file: delete() creates a new directory: mkdir() checks if the file is writable: canwrite() creates a new file: createnewfile() No direct access to file data Use file streams for reading and writing May 29, 2007 19

The File Class Constructors Using a full pathname: File f = new File("/doc/foo.txt"); File dir = new File("/doc/tmp"); Using a pathname relative to the current directory defined in user.dir: File f = new File( foo.txt ); Note: Use System.getProperty('user.dir') to get the value of user.dir (Usually the default is the current directory of the interpreter. In Eclipse it is the project s directory) May 29, 2007 20

The File Class Constructors (cont) File f = new File("/doc","foo.txt"); directory pathname file name File dir = new File("/doc"); File f = new File(dir, "foo.txt"); A File object can be created for a nonexisting file or directory Use exists() to check if the file/dir exists May 29, 2007 21

The File Class Pathnames Pathnames are system-dependent "/doc/foo.txt" (UNIX format) "D:\doc\foo.txt" (Windows format) On Windows platform Java excepts path names either with '/' or '\' The system file separator is defined in: File.separator File.separatorChar May 29, 2007 22

The File Class Directory Listing Printing all files and directories under a given directory: public static void main(string[] args) { File file = new File(args[0]); } String[] files = file.list(); for (int i=0 ; i< files.length ; i++) { System.out.println(files[i]); } May 29, 2007 23

The File Class Directory Listing (cont.) Printing all files and directories under a given directory with ".txt" suffix: public static void main(string[] args) { File file = new File(args[0]); FilenameFilter filter = new SuffixFileFilter(".txt"); } String[] files = file.list(filter); for (int i=0 ; i<files.length ; i++) { System.out.println(files[i]); } May 29, 2007 24

The File Class Directory Listing (cont.) public class SuffixFileFilter implements FilenameFilter { private String suffix; public SuffixFileFilter(String suffix) { this.suffix = suffix; } } public boolean accept(file dir, String name) { return name.endswith(suffix); } May 29, 2007 25

Object Serialization A mechanism that enable objects to be: saved and restored from byte streams persistent (outlive the current process) Useful for: persistent storage sending an object to a remote computer May 29, 2007 26

The Default Mechanism The default mechanism includes: The Serializable interface The ObjectOutputStream The ObjectInputStream Serializable Object write ObjectOutputStream Storage/ Network Serializable Object ObjectInputStream read May 29, 2007 27

The Serializable Interface Objects to be serialized must implement the java.io.serializable interface An empty interface Most objects are Serializable: Primitives, Strings, GUI components etc. Subclasses of Serializable classes are also Serializable May 29, 2007 28

Recursive Serialization Can we serialize a Foo object? public class Foo implements Serializable { } private Bar bar; Foo Bar bar public class Bar { } No, since Bar is not Serializable Solution: Implement Bar as Serializable Mark the bar field of Foo as transient (will not be discussed in the course) And, so on recursively Bar May 29, 2007 29

Writing Objects Writing a HashMap object (map) to a file*: try { FileOutputStream fileout = new FileOutputStream("map.s"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeobject(map); } catch (Exception e) {...} * HashMap is Serializable May 29, 2007 30

Reading Objects try { FileInputStream filein = new FileInputStream("map.s"); ObjectInputStream in = new ObjectInputStream(fileIn); Map h = (Map)in.readObject(); } catch (Exception e) {...} May 29, 2007 31

Other Topics The java.nio package The java.util.zip package May 29, 2007 32