Objec&ves. Review. Standard Error Streams

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

Objec-ves JAR FILES. Jar files. Excep-ons. Files Streams. Ø Wrap up Ø Why Excep-ons? 9/30/16. Oct 3, 2016 Sprenkle - CSCI209 1

CS 251 Intermediate Programming Java I/O Streams

PIC 20A Streams and I/O

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

Lecture 11.1 I/O Streams

Darshan Institute of Engineering & Technology for Diploma Studies

I/O Streams. Object-oriented programming

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

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

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

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

10/7/15. MediaItem tostring Method. Objec,ves. Using booleans in if statements. Review. Javadoc Guidelines

Software 1. Java I/O

CSC 1214: Object-Oriented Programming

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

Object-Oriented Programming Design. Topic : Streams and Files

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

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

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

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

Simple Java Input/Output

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

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

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

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Programming Languages and Techniques (CIS120)

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Experiment No: Group B_4

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

Example: Copying the contents of a file

Java Input/Output. 11 April 2013 OSU CSE 1

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

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

1.00 Lecture 30. Sending information to a Java program

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

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

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

Chapter 10. IO Streams

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

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

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

IT101. File Input and Output

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

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

Exceptions and Working with Files

Programming Languages and Techniques (CIS120)

Performing input and output operations using a Byte Stream

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

CSD Univ. of Crete Fall Files, Streams, Filters

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Software Practice 1 - File I/O

CS193j, Stanford Handout #26. Files and Streams

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

Programming Languages and Techniques (CIS120)

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

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

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

C17: I/O Streams and File I/O

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

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

Introduction Unit 4: Input, output and exceptions

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

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

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

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

Object-Oriented Programming in the Java language

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

Sri Vidya College of Engineering & Technology Question Bank

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

Chapter 10 Input Output Streams

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

C17: File I/O and Exception Handling

ITI Introduction to Computer Science II

Principles of Software Construction: Objects, Design and Concurrency. Design Case Study: Stream I/O. toad

File Processing in Java

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

27 Trying it 28 Trying it 29 Coursework: A check sum program 30 Section 3: Example:Counting characters from standard input 31 Aim 32 Counting characte

Lab 2: File Input and Output

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

Input from Files. Buffered Reader

Dining philosophers (cont)

DM550 Introduction to Programming part 2. Jan Baumbach.

Jonathan Aldrich Charlie Garrod

Techniques of Java Programming: Streams in Java

HST 952. Computing for Biomedical Scientists Lecture 8

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Files and Streams

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

Internet Technology 2/7/2013

I/O Streams. COMP 202 File Access. Standard I/O. I/O Stream Categories

CPS122 Lecture: Input-Output

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

Simple Java I/O. Part I General Principles

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Java Console Input/Output The Basics

Transcription:

Objec&ves Standard Error Streams Ø Byte Streams Ø Text Streams Oct 5, 2016 Sprenkle - CSCI209 1 Review What are benefits of excep&ons What principle of Java do files break if we re not careful? What class did we use to read from standard in? What abstrac&on do we use to do I/O in Java? What are some ways to categorize streams? Ø When would you use these streams? Oct 5, 2016 Sprenkle - CSCI209 2 1

STANDARD ERROR Oct 5, 2016 Sprenkle - CSCI209 3 Standard Streams Preconnected streams Ø Standard Out: stdout Ø Standard In: stdin Ø Standard Error: stderr For error messages and diagnos&cs In Java: System.err Benefits of two output streams (out and err)? Oct 5, 2016 Sprenkle - CSCI209 4 2

Standard Streams Preconnected streams Ø Standard Out: stdout Ø Standard In: stdin Ø Standard Error: stderr For error messages and diagnos&cs In Java: System.err Benefits of two output streams Ø Redirect to different places Example: separate log files for info and for errors Oct 5, 2016 Sprenkle - CSCI209 5 RETURNING TO SCANNER Oct 5, 2016 Sprenkle - CSCI209 6 3

java.util.scanner New(er) class for handling input Ø Since Java 1.5 Many constructors Ø Read from file, input stream, string Scanner sc = new Scanner(System.in); Many methods Ø nextxxxx (int, long, line) Ø Skipping payerns, matching payerns, etc. Oct 3, 2016 Sprenkle - CSCI209 7 Scanners Breaks its input into tokens using a delimiter payern, which matches whitespace What is delimiter pattern? What is whitespace? Converts resul&ng tokens into values of different types using nextxxx() Can change token delimiter from default of whitespace Assumes numbers are input as decimal Ø Can specify a different radix Oct 3, 2016 Sprenkle - CSCI209 8 4

Using Scanners Use nextxxx() to read from it long templong; // create the scanner for the console Scanner sc = new Scanner(System.in); // read in an integer and a String int i = sc.nextint(); String restofline = sc.nextline(); // read in a bunch of long integers while (sc.hasnextlong()) { templong = sc.nextlong(); } Oct 3, 2016 Sprenkle - CSCI209 9 Using Scanner Simplified version of online example public static void main(string[] args) { // open the Scanner on the console input, System.in Scanner scan = new Scanner(System.in); scan.usedelimiter("\n"); // breaks up by lines, useful for // console I/O System.out.print("Please enter the width of a rectangle: "); int width = scan.nextint(); System.out.print("Please enter the height of a rectangle: "); int length = scan.nextint(); System.out.println("The area of your square is " + length * width + "."); } ConsoleUsingScannerDemo.java Oct 3, 2016 Sprenkle - CSCI209 10 5

Output Read in as one token This program calculates the area of a rectangle. Please enter the width of a rectangle (as an integer): the number is 1 Incorrect input. Please enter the width of a rectangle (as an integer): 1 2 Incorrect input. Please enter the width of a rectangle (as an integer): 2 Please enter the height of a rectangle (as an integer): 3 The area of your rectangle is 6. Oct 3, 2016 Sprenkle - CSCI209 11 Scanners & Excep&ons Scanners do not throw IOExceptions! Ø For a simple console program, main() does not have to deal with or throw IOExceptions Ø Required with BufferedReader/ InputStreamReader combina&on Throws InputMismatchException when token doesn t match payern for expected type Ø e.g., nextlong() called with next token AAA Ø RuntimeException (no catching required) How do you prevent such errors? Oct 3, 2016 Sprenkle - CSCI209 12 6

Console class Get a Console object using System.console() Has some useful methods for requesting passwords Issue: does not work through an IDE ConsoleUsingConsoleDemo.java Oct 3, 2016 Sprenkle - CSCI209 13 STREAMS Oct 5, 2016 Sprenkle - CSCI209 14 7

Streams Java handles input/output using streams, which are sequences of bytes input stream: an object from which we can read a sequence of bytes abstract class: java.io.inputstream Oct 5, 2016 Sprenkle - CSCI209 15 Streams Java handles input/output using streams, which are sequences of bytes output stream: an object to which we can write a sequence of bytes abstract class: java.io.outputstream Oct 5, 2016 Sprenkle - CSCI209 16 8

java.io Classes Overview Two types of stream classes, based on type of data: Byte, Text Abstract base classes for binary data: InputStream OutputStream Abstract base classes for text data: Reader Writer How will you know what type of data you have? Oct 5, 2016 Sprenkle - CSCI209 17 Byte Streams For binary data In java.io package Abstract Base Classes Shaded: Read to/write from data sinks White: Does some processing Oct 5, 2016 Sprenkle - CSCI209 18 9

File Input and Output Streams FileInputStream: provides an input stream that can read from a file Ø Constructor takes the name of the file: FileInputStream fin = new FileInputStream("chicken.data"); Ø Or, uses a File object File inputfile = new File("chicken.data"); FileInputStream fin = new FileInputStream(inputFile); FileTest.java Oct 5, 2016 Sprenkle - CSCI209 19 More Powerful Stream Objects DataInputStream Ø Reads Java primi&ve types through methods such as readdouble(), readchar(), readboolean() DataOutputStream Ø Writes Java primi&ve types with writedouble(), writechar(), Oct 5, 2016 Sprenkle - CSCI209 20 10

Connected Streams Our goal: read numbers from a file FileInputStream can read from a file but has no methods to read numeric types DataInputStream can read numeric types but has no methods to read from a file Java allows you to combine two types of streams into a connected stream Ø FileInputStream à chocolate Ø DataInputStream à peanut buyer Oct 5, 2016 Sprenkle - CSCI209 21 Connected Streams Think of a stream as a pipe FileInputStream knows how to read from a file DataInputStream knows how to read an InputStream into useful types Connect out end of FileInputStream to in end of DataInputStream file char FileInputStream DataInputStream Data Source stream double Filtered Stream Reads from a stream Oct 5, 2016 Sprenkle - CSCI209 22 11

Connec&ng Streams If we want to read numbers from a file Ø FileInputStream reads bytes from file Ø DataInputStream handles numeric type reading Connect the DataInputStream to the FileInputStream Ø FileInputStream gets the bytes from the file and DataInputStream reads them as assembled types FileInputStream fin = new FileInputStream("chicken.data"); DataInputStream din = new DataInputStream(fin); wrap fin in din double num1 = din.readdouble(); DataIODemo.java Oct 5, 2016 Sprenkle - CSCI209 23 Data Source vs. Filtered Streams Data Source Streams Communicate with a data source Ø file, byte array, network socket, or URL Filtered Streams Subclasses of FilterInputStream or FilterOutputStream Always contains another stream Adds functionality to other stream Ø Automatically buffered IO Ø Automatic compression Ø Automatic encryption Ø Automatic conversion between objects and bytes Oct 5, 2016 Sprenkle - CSCI209 24 12

Buffered Streams Use a BufferedInputStream object to buffer your input streams Ø A pipe in the chain that adds buffering Ø Speeds up access DataInputStream din = new DataInputStream ( new BufferedInputStream ( new FileInputStream("chicken.data"))); file FileInputStream BufferedInputStream DataInputStream char double What functionality does each stream add? Oct 5, 2016 Sprenkle - CSCI209 25 Connected Streams: Output Combine different types of streams to get functionality you want Similar for output Ø For buffered output to the file and to write types Create a FileOutputStream AYach a BufferedOutputStream AYach a DataOutputStream Perform typed wri&ng using methods of the DataOutputStream object Oct 5, 2016 Sprenkle - CSCI209 26 13

Connected Streams Combine different types of streams to get functionality you want What are the tradeoffs for this design decision? Oct 5, 2016 Sprenkle - CSCI209 27 Connected Streams Combine different types of streams to get functionality you want Crea&ng a class for every class would result in even more classes and a lot of redundant code Ø Consider what is required if some func&onality must be updated Oct 5, 2016 Sprenkle - CSCI209 28 14

TEXT STREAMS Oct 5, 2016 Sprenkle - CSCI209 29 Text Streams Previous streams: operate on binary data, not text Java uses Unicode to represent characters/strings and some opera&ng systems do not Ø Need something that converts characters from Unicode to whatever encoding the underlying opera&ng system uses Ø Luckily, this is mostly hidden from you Oct 5, 2016 Sprenkle - CSCI209 30 15

Character Streams For Text In java.io package Handle any character in Unicode set Abstract Base Classes Shaded: Read to/write from data sinks White: Does some processing Oct 5, 2016 Sprenkle - CSCI209 31 Text Streams Derived from Reader and Writer classes Ø Reader and Writer generally refer to text I/O Example: Make an input reader of type InputStreamReader that reads from keyboard InputStreamReader in = new InputStreamReader(System.in); Ø in reads characters from keyboard and converts them into Unicode for Java Oct 5, 2016 Sprenkle - CSCI209 32 16

Text Streams and Encodings AYach an InputStreamReader to a FileInputStream InputStreamReader in = new InputStreamReader( new FileInputStream("employee.data")); Ø Assumes file has been encoded in the default encoding of underlying OS You can specify a different encoding in constructor of InputStreamReader InputStreamReader in = new InputStreamReader( new FileInputStream("employee.data"), "UTF-8"); Oct 5, 2016 Sprenkle - CSCI209 33 Convenience Classes Reading and wri&ng to text files is common FileReader Ø Convenience class combines a InputStreamReader with a FileInputStream Similar for output of text file FileWriter out = new FileWriter("output.txt"); is equivalent to OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream("output.txt")); Oct 5, 2016 Sprenkle - CSCI209 34 17

PrintWriter Use for wri&ng text output Ø Easiest writer to use Similar to a DataOutputStream, PrintStream à has methods for printing various data types Methods: print, printf and println Ø Similar to System.out (a PrintStream) to display strings Oct 5, 2016 Sprenkle - CSCI209 35 PrintWriter Example File to write to PrintWriter out = new PrintWriter("output.txt"); String myname = "Homer Simpson"; double mysalary = 35700; out.print(myname); out.print(" makes "); out.print(salary); out.println(" per year."); or out.println(myname + " makes " + salary + " per year."); Oct 5, 2016 Sprenkle - CSCI209 36 18

Review: FormaYed Output printf or format Ø PrintStream new func&onality since Java 1.5 double f1=3.14159, f2=1.45, total=9.43; // simple formatting... System.out.printf("%6.5f and %5.2f", f1, f2); // getting fancy (%n = \n or \r\n)... System.out.printf("%-6s%5.2f%\n", "Tax:", total); Oct 5, 2016 Sprenkle - CSCI209 37 Reading Text from a Stream Use a BufferedReader Ø Constructor requires a Reader object BufferedReader in = new BufferedReader( new FileReader("inputfile.txt")); Read file, line-by-line using readline() Ø Reads in a line of text and returns it as a String Ø Returns null when no more input is available String line; while ((line = in.readline())!= null) { // process the line } Oct 5, 2016 Sprenkle - CSCI209 38 19

Reading Text from a Stream You can also ayach a BufferedReader to an InputStreamReader: BufferedReader consolereader= new BufferedReader( new InputStreamReader(System.in)); BufferedReader webpagereader = new BufferedReader( new InputStreamReader(url.openStream()); Note how easy it is to read from different sources Oct 5, 2016 Sprenkle - CSCI209 39 Prac&ce Reading from and wri&ng to a file PetSurvey.java Oct 5, 2016 Sprenkle - CSCI209 40 20

Looking Ahead Exam: Friday Ø Faculty Rep to Board of Trustees not available most of the day outside of class Assign 7: Wednesday Ø Modifying Olympic Score generator Ø Read difficulty score from console Ø Read execu&on scores from a file Ø Filename comes from console Monday Ø Java vs Python capstone to this part of the course Oct 5, 2016 Sprenkle - CSCI209 41 21