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

Similar documents
Lecture 11.1 I/O Streams

CSC 1214: Object-Oriented Programming

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

Darshan Institute of Engineering & Technology for Diploma Studies

Java Input/Output. 11 April 2013 OSU CSE 1

copy.dept_change( CSE ); // Original Objects also changed

CS 251 Intermediate Programming Java I/O Streams

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

Programming Languages and Techniques (CIS120)

Object-Oriented Programming Design. Topic : Streams and Files

Programming Languages and Techniques (CIS120)

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

Programming Languages and Techniques (CIS120)

PIC 20A Streams and I/O

Software Practice 1 - File I/O

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

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

Objec&ves. Review. Standard Error Streams

IT101. File Input and Output

Simple Java Input/Output

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

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

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

Programming Languages and Techniques (CIS120)

ITI Introduction to Computer Science II

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

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

Techniques of Java Programming: Streams in Java

I/O STREAM (REQUIRED IN THE FINAL)

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

Chapter 10 Input Output Streams

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

Programming Languages and Techniques (CIS120)

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

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

Sri Vidya College of Engineering & Technology Question Bank

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

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

Character Stream : It provides a convenient means for handling input and output of characters.

1.00 Lecture 30. Sending information to a Java program

I/O Streams. Object-oriented programming

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Exceptions and Working with Files

Input & Output in Java. Standard I/O Exception Handling

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

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

Internet Technology 2/7/2013

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

Chapter 10. IO Streams

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

File Processing in Java

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

Example: Copying the contents of a file

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

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

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

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

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

Each command-line argument is placed in the args array that is passed to the static main method as below :

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

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

23 Error Handling What happens when a method is called? 23.1 What is Exception Handling? A.m() B.n() C.p()

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

HST 952. Computing for Biomedical Scientists Lecture 8

Lab 10: Sockets 12:00 PM, Apr 4, 2018

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

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

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

Data Types and the while Statement

Files and Streams

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Experiment No: Group B_4

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

Introduction Unit 4: Input, output and exceptions

C17: File I/O and Exception Handling

Lecture 4: Exceptions. I/O

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

CSCI Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship. Java Review: Execution, IO & Java 5

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

Streams and File I/O

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

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

Lab 2: File Input and Output

CPSC 319. Week 2 Java Basics. Xiaoyang Liu & Sorting Algorithms

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

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

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

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Chettinad College of Engineering & Technology Department of Information Technology Internal Examination II (Answer Key)

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

Software 1. Java I/O

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

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

Program Elements -- Introduction

Object Oriented Software Design

Object Oriented Software Design

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

Transcription:

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

I/O basics The io package supports Java s basic I/O (input/output) Java does provide strong, flexible support for I/O as it relates to files and networks. Java s I/O system is cohesive and consistent. In fact, once you understand its fundamentals, the rest of the I/O system is easy to master, including file I/O. 2

STREAMS A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket Likewise, an output stream may refer to the console, a disk file, or a network connection.. Java implements streams within class hierarchies defined in the java.io package. 3

4

BYTE AND CHARACTER STREAMS Java defines two types of streams: byte and character. Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. Character streams provide a convenient means for handling input and output of characters. 5

The Byte Stream Classes The Byte Stream Classes Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. Each of these abstract classes has several concrete subclasses that handle the differences among various devices, such as disk files, network connections, and even memory buffers. 6

Character stream classes The Character Stream Classes Character streams are defined by using two class hierarchies. At the top are two abstract classes: Reader and Writer. These abstract classes handle Unicode character streams. Java has several concrete subclasses of each of these 8

Predefined streams This package defines a class called java.lang.system, which encapsulates several aspects of the run-time environment. System extends Object class System also contains three predefined stream variables(objects): in, out, and err. These fields are declared as public, static, and final within System. This means that they can be used by any other part of your program and without reference to a specific System object. 10

System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default. However, these streams may be redirected to any compatible I/O device. System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream. These are byte streams, even though they are typically used to read and write characters from and to the console. 11

Reading Console Input the only way to perform console input was to use a byte stream. for commercial applications, the preferred method of reading console input is to use a character-oriented stream Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object. BufferedReader supports a buffered input stream 12

BufferedReader A commonly used constructor is shown here: BufferedReader(Reader inputreader) Here, inputreader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. 13

BufferedReader To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputstream) Because System.in refers to an object of type InputStream, it can be used for inputstream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); After this statement executes, br is a character-based stream that is linked to the console through System.in. 14

Reading Characters To read a character from a BufferedReader, use read( ). The version of read( ) that we will be using is int read( ) throws IOException Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns 1 when the end of the stream is encountered. As you can see, it can throw an IOException. 15

import java.io.*; class BRRead { public static void main(string args[]) throws IOException { char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter characters, 'q' to quit."); // read characters do { c = (char) br.read(); //read() gives integer System.out.println(c); while(c!= 'q'); Here is a sample run: Enter characters, 'q' to quit. 1 2 3 a b c q This means that no input is actually passed to the program until you press enter. 16

Reading Strings To read a string from the keyboard, use the version of readline( ) that is a member of the BufferedReader class. Its general form is shown here: String readline( ) throws IOException As you can see, it returns a String object. 17

The following program demonstrates BufferedReader and the readline( ) method; the program reads and displays lines of text until you enter the word "stop": // Read a string from console using a BufferedReader. import java.io.*; class BRReadLines { public static void main(string args[]) throws IOException { // create a BufferedReader using System.in Output: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); do { str = br.readline(); System.out.println(str); while(!str.equals("stop")); Enter lines of text. Enter stop to quit. Hi This is Ashish I am teaching Java Byeeeee stop 18

EXAMPLE PROGRAM Write a program to create a tiny text editor. It creates an array of String objects and then reads in lines of text, storing each line in the array. It will read up to 100 lines or until you enter "stop. It uses a BufferedReader to read from the console. 19

// A tiny editor. import java.io.*; class TinyEdit { public static void main(string args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str[] = new String[100]; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); 20

for(int i=0; i<100; i++) { str[i] = br.readline(); if(str[i].equals("stop")) break; System.out.println("\nHere is your file:"); // display the lines for(int i=0; i<100; i++) { if(str[i].equals("stop")) break; System.out.println(str[i]); Here is a sample run: Enter lines of text. Enter 'stop' to quit. This is line one. This is line two. Java makes working with strings easy. Just create String objects. stop Here is your file: This is line one. This is line two. Java makes working with strings easy. Just create String objects. 21

Writing Console Output Console output is most easily accomplished with print( ) and println( ), described earlier, These methods are defined by the class PrintStream (which is the type of object referenced by System.out). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is shown here: void write(int byteval) This method writes the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written. Here is a short example that uses write( ) to output 22

// Demonstrate System.out.write(). class WriteDemo { public static void main(string args[]) { int b; b = 'A'; System.out.write(b); System.out.write('\n'); You will not often use write( ) to perform console output (although doing so might be useful in some situations) because print( ) and println( ) are substantially easier to use. 23

// Demonstrate System.out.write(). class WriteDemo { public static void main(string args[]) { int b; b = 'A'; System.out.write(b); System.out.write('\n'); Output is You will not often use write( ) to perform console output (although doing so might be useful in some situations) because print( ) and println( ) are substantially easier to use. A 24

The PrintWriter Class For real world programs, the recommended method of writing to the console when using Java is through a PrintWriter stream. PrintWriter is one of the character-based classes. PrintWriter defines several constructors. The one we will use is shown here: PrintWriter(OutputStream outputstream, boolean flushingon) 25

The PrintWriter Class Here, outputstream is an object of type OutputStream, and flushingon controls whether Java flushes the output stream every time a println( ) method (among others) is called. If flushingon is true, flushing automatically takes place. If false, flushing is not automatic. For example, this line of code creates a PrintWriter that is connected to console output: PrintWriter pw = new PrintWriter(System.out, true); 26

EXAMPLE PRINTWRITER The following application illustrates using a PrintWriter to handle console output: // Demonstrate PrintWriter import java.io.*; public class PrintWriterDemo { public static void main(string args[]) { PrintWriter pw = new PrintWriter(System.out, true); pw.println("this is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); 27

EXAMPLE PRINTWRITER The following application illustrates using a PrintWriter to handle console output: // Demonstrate PrintWriter import java.io.*; public class PrintWriterDemo { public static void main(string args[]) { PrintWriter pw = new PrintWriter(System.out, true); pw.println("this is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); The output from this program is shown here: This is a string -7 4.5E-7 28

EXAMPLE PRINTWRITER There is nothing wrong with using System.out to write simple text output to the console when you are learning Java or debugging your programs. However, using a PrintWriter makes your real-world applications easier to internationalize 29