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

Similar documents
Darshan Institute of Engineering & Technology for Diploma Studies

Objec&ves. Review. Standard Error Streams

Software Practice 1 - File I/O

Lecture 11.1 I/O Streams

PIC 20A Streams and I/O

CS 251 Intermediate Programming Java I/O Streams

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

Java Input/Output. 11 April 2013 OSU CSE 1

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

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

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

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

Software 1. Java I/O

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

1.00 Lecture 30. Sending information to a Java program

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

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

Exceptions and Working with Files

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

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

IT101. File Input and Output

Example: Copying the contents of a file

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

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

Object-Oriented Programming Design. Topic : Streams and Files

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

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

CSC 1214: Object-Oriented Programming

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

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

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

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

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

Programming Languages and Techniques (CIS120)

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

Simple Java Input/Output

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

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

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

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

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

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

HST 952. Computing for Biomedical Scientists Lecture 8

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

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

Programming Languages and Techniques (CIS120)

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

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

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

Streams and File I/O

Object-Oriented Programming in the Java language

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

Chapter 10. IO Streams

ITI Introduction to Computer Science II

Programming Languages and Techniques (CIS120)

I/O Streams. Object-oriented programming

Starting Out with Java: From Control Structures Through Objects Sixth Edition

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

C17: I/O Streams and File I/O

CS Programming I: File Input / Output

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

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

Performing input and output operations using a Byte Stream

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

Lesson 3: Accepting User Input and Using Different Methods for Output

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

CS112 Lecture: Streams

Lab 5: Java IO 12:00 PM, Feb 21, 2018

CSD Univ. of Crete Fall Files, Streams, Filters

Programming Languages and Techniques (CIS120)

CS Programming I: File Input / Output

WOSO Source Code (Java)

Programming Languages and Techniques (CIS120)

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

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

Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO. Understanding Board

Lab 2: File Input and Output

C17: File I/O and Exception Handling

I/O STREAM (REQUIRED IN THE FINAL)

Chapter 12. File Input and Output. CS180-Recitation

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

CPS122 Lecture: Input-Output

pre-emptive non pre-emptive

Today s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO

Course Content. Objectives of Lecture 22 File Input/Output. Outline of Lecture 22. CMPUT 102: File Input/Output Dr. Osmar R.

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

CPS122 Lecture: Input-Output

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

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

Input from Files. Buffered Reader

Dining philosophers (cont)

File Processing in Java

Introduction Unit 4: Input, output and exceptions

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

CS193j, Stanford Handout #26. Files and Streams

Files and Streams

CN208 Introduction to Computer Programming

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

Transcription:

I/O 10-7-2013

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

public class Swimmer implements Cloneable { public Date geteventdate() { return (Date) eventdate.clone(); // note: Date must be cloneable } } Exercise: rewrite the above to use a copy constructor rather than clone to solve the problem

key ideas: Separate the classes that read and write bytes from the classes that interpret and format the data Layering: start with a stream & wrap other classes around it to add functionality consequence - networking is facilitated

package java.io (also see java.nio) text: Reader, Writer binary: InputStream, OutputStream converting from stream to text: InputStreamReader buffering: BufferedReader package java.util Scanner

InputStream OutputStream Reader Writer byte-oriented I/O (8-bit) binary data machine-readable only char-oriented I/O (16-bit) text data human-readable RandomAccess binary key idea: layered object start with a stream & wrap other classes around it to add functionality

standard input, standard output & standard error (default to console, but can be redirected to any stream) defined in the class System (which is in java.lang) public static final InputStream in; public static final PrintStream out; public static final PrintStream err

try { int b = System.in.read(); } catch (IOException e) OK for reading in a single byte of raw data, but what about numbers (int, float, ) or a line of text? Would like to use readline(), but to do this you need a buffered reader, not a Stream like System.in use InputStreamReader to convert from a Stream to a Reader then can use the method readline() in BufferedReader

public String readline() throws IOException Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed. Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached Throws: IOException - If an I/O error occurs

constructors for InputStreamReader include: InputStreamReader( InputStream in ); constructors for BufferedReader include: BufferedReader( Reader rin ); constructors for Scanner include: Scanner( InputStream source ); Scanner( File source ); Scanner( String source );

Choose one of the abstract classes Wrap functionality around it (buffers, files, compression, etc.) Format, if desired java.text package handles fonts, precision, internationalism, etc BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) )

// Read and echo lines until EOS public static final String EOS = null; try { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); String inline; while (( inline = stdin.readline())!= EOS) System.out.println(inLine); stdin.close(); } catch (IOException e)

// Read an int from standard input try { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); String inline = stdin.readline(); int val = Integer.parseInt(inLine); Two potential errors System.out.println( Integer value is: + val); } catch (NumberFormatException e) { System.err.println(inLine + is not an int ); } catch (IOException e) { System.err.println( Unexpected IO error: + e); } error message written to Standard Error

Input InputStreamReader BufferedReader Output OutputStreamReader BufferedWriter PrintWriter, PrintStream FileReader StringReader DataInputStream ObjectInputStream ZipInputStream GZIPInputStream FileWriter StringWriter DataOutputStream ObjectOutputStream ZipOutputStream GZIPOutputStream

System.out.println("Hello" + new Date()); System.out is a PrintStream (OutputStream + ability to print data) doesn't throw Exceptions (can use method checkerror() to detect errors) println() method is polymorphic Object, String, int, float, char[], boolean + is polymorphic a + b can mean String concatenation or addition, depending on what a and b are

println adds the correct end-of-line characters for the target OS \r\n in Windows \n in Unix \r in Mac System.getProperty("line.separator") returns this string of end-of-line characters

// tostring revisited public class MyClass { private String myname; problem: platform-dependent public String tostring() { return "BadNewline@" + "\n" + myname; } public static void main(string[] args) { MyClass jack = new MyClass("Jack Frost"); System.out.println(jack); }

// tostring revisited public class BetterClass { private String myname; public static final String NEWLINE = System.getProperty( line.separator ); platform-independent public String tostring() { return GoodNewline@" + NEWLINE + myname; } public static void main(string[] args) { BetterClass jack = new BetterClass("Jack Frost"); System.out.println(jack); }

BufferedReader indata = new BufferedReader( new InputStreamReader(System.in) ); data source

BufferedReader indata = new BufferedReader( new FileReader( mydata.txt ) ); data source

default: current directory BufferedReader indata = new BufferedReader( new FileReader( mydata.txt )); or File filepath = new File( c:\\cs242\\ ); BufferedReader indata = new BufferedReader( new FileReader(filePath, mydata.txt )); class File is an abstract representation of file and directory pathnames (java.io.file, cf. p 452 HFJ2)

public FileReader(String filename) throws FileNotFoundException Creates a new FileReader, given the name of the file to read from. Parameters: filename - the name of the file to read from Throws: FileNotFoundException - if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.

try { BufferedReader stdin = new BufferedReader( new FileReader( mydata.txt )); Read an integer from the file mydata.txt

try { BufferedReader stdin = new BufferedReader( new FileReader( mydata.txt )); Read an integer from the file mydata.txt String inline = stdin.readline(); int val = Integer.parseInt(inLine); System.out.println( Integer value is: + val);

try { BufferedReader stdin = new BufferedReader( new FileReader( mydata.txt )); Read an integer from the file mydata.txt String inline = stdin.readline(); int val = Integer.parseInt(inLine); System.out.println( Integer value is: + val); } catch (NumberFormatException e) { System.err.println(inLine + is not an int );

try { BufferedReader stdin = new BufferedReader( new FileReader( mydata.txt )); Read an integer from the file mydata.txt String inline = stdin.readline(); int val = Integer.parseInt(inLine); System.out.println( Integer value is: + val); } catch (NumberFormatException e) { System.err.println(inLine + is not an int ); } catch (FileNotFoundException e) { System.err.println( Could not open file for reading );

Read an integer from the file mydata.txt try { BufferedReader stdin = new BufferedReader( new FileReader( mydata.txt )); String inline = stdin.readline(); int val = Integer.parseInt(inLine); System.out.println( Integer value is: + val); } catch (NumberFormatException e) { System.err.println(inLine + is not an int ); } catch (FileNotFoundException e) { System.err.println( Could not open file for reading ); } catch (IOException e) { System.err.println( Unexpected IO error: + e); }

// Read and echo lines, using BufferedReader public static final String EOS = null; try { BufferedReader stdin = new BufferedReader( new FileReader( MyData.txt )); String inline; while (( inline = stdin.readline())!= EOS) System.out.println(inLine); stdin.close(); } catch (IOException e) {

Java 1.5 introduced a new class: Scanner that makes it easy to read and parse strings and primitive types using regular expressions (class java.util.regex.pattern) constructors include: Scanner( File pathname ); Scanner( InputStream is ); Scanner( String aline );

try { Scanner scan = new Scanner( System.in ); Use Scanner to read an int from standard input int val = scan.nextint(); System.out.println( Integer value is: + val); } catch (InputMismatchException e) { System.err.println( Did not input an int ); } catch // what other exceptions?

Use Scanner to read an int from a text file try { Scanner scan = new Scanner( new File( mydata.txt ) ); int val = scan.nextint(); System.out.println( Integer value is: + val); } catch (InputMismatchException e) { System.err.println( Did not input an int ); } catch (FileNotFoundException e) { System.err.println( Couldn t open file for reading ); } catch // what other exceptions?

try { BufferedReader stdin = new BufferedReader( new FileReader( sample.txt )); String inline = stdin.readline(); int val = Integer.parseInt(inLine); System.out.println( Integer value is: + val); } catch (NumberFormatException e) { System.err.println(inLine + is not an int ); } catch (FileNotFoundException e) { System.err.println( Could not open file for reading ); } catch (IOException e) { } Read an integer from the file mydata.txt System.err.println( Unexpected IO error: + e);

try { Scanner scan = new Scanner( new File( sample.txt )); Java 1.5 Scanner class int val = scan.nextint(); System.out.println( Integer value is: + val); } catch (InputMismatchException e) { System.err.println( Next token is not an int ); } catch (FileNotFoundException e) { System.err.println( Could not open file for reading ); } catch (IOException e) { System.err.println( Unexpected IO error: + e); }

Use BufferedReader to read an int from standard input try { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); String inline = stdin.readline(); int val = Integer.parseInt(inLine); System.out.println( Integer value is: + val); } catch (NumberFormatException e) { System.err.println(inLine + is not an int ); } catch (IOException e) { System.err.println( Unexpected IO error: + e); }

try { BufferedReader stdin = new BufferedReader( new FileReader( mydata.txt ) ); Use BufferedReader to read an int from a text file String inline = stdin.readline(); int val = Integer.parseInt(inLine); System.out.println( Integer value is: + val); } catch (NumberFormatException e) { System.err.println(inLine + is not an int ); } catch (FileNotFoundException e) { System.err.println( Couldn t open file for reading ); } catch (IOException e) { System.err.println( Unexpected IO error: + e); }

consider the text 1342 Unicode: 00 31 00 33 00 34 00 32 most environments use their own char encoding; e.g. windows: 31 33 34 32 Java provides conversion filters from Unicode to the char encoding used by the local OS

InputStreamReader converts an input stream containing bytes in a particular char encoding into a reader that emits Unicode chars public InputStreamReader(InputStream in, CharsetDecoder dec) OutputStreamReader is similar

The char data type is based on the original Unicode specification, which defined characters as fixed-width 16-bit entities. The Unicode Standard has since been changed to allow for characters whose representation requires more than 16 bits. For more information on Unicode 6.2.0, see www.unicode.org.

e.g. read keystrokes from console (recall that System.in is an InputStream), and convert to Unicode: A.. Z \u0041.. \u005a a.. z \u0061.. \u007a 0.. 9 \u0030.. \u0039 InputStreamReader isr = new InputStreamReader(System.in); int x = isr.read(); user types 4 what is x (in decimal)? 52 (hex 34)

See www.unicode.org/charts/ 8859_1 ISO Latin-1 (default) 8859_5 ISO Latin/Cyrillic Big4 Traditional Chinese etc. So, to open a file using one of these, you would call new InputStreamReader( new FileInputStream( mydata ), 8859_5 ) Cyrillic