CSC 1214: Object-Oriented Programming

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

Lecture 11.1 I/O Streams

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

PIC 20A Streams and I/O

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

Darshan Institute of Engineering & Technology for Diploma Studies

Software 1. Java I/O

Exceptions and Working with Files

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

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

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

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

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

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

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

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

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

Objec&ves. Review. Standard Error Streams

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

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

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

Example: Copying the contents of a file

1.00 Lecture 30. Sending information to a Java program

Experiment No: Group B_4

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

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

Object-Oriented Programming Design. Topic : Streams and Files

Reading and Writing Files

I/O Streams. Object-oriented programming

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

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

Java Input/Output. 11 April 2013 OSU CSE 1

CS 251 Intermediate Programming Java I/O Streams

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

CSD Univ. of Crete Fall Files, Streams, Filters

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

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

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

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.

Software Practice 1 - File I/O

Writing usable APIs in practice

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

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

Writing usable APIs in practice

Chapter 10. IO Streams

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

ITI Introduction to Computer Science II

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

Programming Languages and Techniques (CIS120)

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

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

IT101. File Input and Output

Chapter 10 Input Output Streams

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

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

Java IO and C++ Streams

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

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

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

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

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

Simple Java Input/Output

Programming Languages and Techniques (CIS120)

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

Introduction to Java

I/O STREAM (REQUIRED IN THE FINAL)

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

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.

Programming Languages and Techniques (CIS120)

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

ing execution. That way, new results can be computed each time the Class The Scanner

Chapter 8: Files and Security

CS Programming I: File Input / Output

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

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

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

Performing input and output operations using a Byte Stream

10.1 Overview 162 CHAPTER 10 CHARACTER STREAMS

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

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

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

Jonathan Aldrich Charlie Garrod

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

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

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

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

CS Programming I: File Input / Output

Dining philosophers (cont)

CS 200 File Input and Output Jim Williams, PhD

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

CS Week 11. Jim Williams, PhD

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

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

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

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

C17: I/O Streams and File I/O

Transcription:

CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: www: materials: e-learning environment: office: alt. office: jkizito@cis.mak.ac.ug http://serval.ug/~jona http://serval.ug/~jona/materials/csc1214 http://muele.mak.ac.ug block A, level 3, wing B, rm 304B institute of open, distance, and elearning, rm D20 Java Input/Output (I/O) Kizito (Makerere University) CSC 1214 May, 2017 1 / 22

Overview 1 Java I/O I/O Streams Predefined Streams Console I/O File I/O Kizito (Makerere University) CSC 1214 May, 2017 2 / 22

Java I/O Introduction Apart from print() and println(), none of the I/O methods have been used significantly because most real applications of Java are not text-based, console programs Java provides strong, flexible support for I/O as it relates to files and networks Java programs perform I/O through streams Kizito (Makerere University) CSC 1214 May, 2017 3 / 22

I/O Streams Java I/O I/O 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 An input stream can abstract many different kinds of input: disk file, keyboard, network socket An output stream may refer to the console, disk file, or network connection Java implements streams within class hierarchies defined in the java.io package Kizito (Makerere University) CSC 1214 May, 2017 4 / 22

I/O Streams Java I/O Byte streams and Character streams Java 2 defines two types of classes: byte and character Byte streams provide a convenient means for handling input and output of bytes Character streams provide a convenient means for handling input and output of characters In some cases, character streams are more efficient than byte streams The Byte Stream Defined by using two class hierarchies At the top are two abstract classes: InputStream and OutputStream These classes define several key methods including read() and write(), which, respectively, read and write bytes of data The Character Stream Defined by using two class hierarchies At the top are two abstract classes: Reader and Writer These classes define several key methods including read() and write(), which read and write characters of data, respectively Kizito (Makerere University) CSC 1214 May, 2017 5 / 22

I/O Streams java.io Kizito (Makerere University) CSC 1214 May, 2017 6 / 22

I/O Streams BufferedInputStream BufferedOutputStream ByteArrayInputStream ByteArrayOutputStream DataInputStream DataOutputStream FileInputStream FileOutputStream FilterInputStream FilterOutputStream InputStream OutputStream PipedInputStream PipedOutputStream PrintStream PushBackInputStream RandomAccessFile SequenceInputStream The Byte Stream Classes Reads from a byte array Writes to a byte array Reading Java standard data types Writing Java standard data types Reads from a file Writes to a file Implements InputStream Implements OutputStream Abstract class Abstract class Input pipe Ouyput pipe Contains print() and println() Supports one-byte unget returns a byte to the input stream Random access file I/O Combination of two or more input streams that will be read sequentially Kizito (Makerere University) CSC 1214 May, 2017 7 / 22

I/O Streams java.io.inputstream Kizito (Makerere University) CSC 1214 May, 2017 8 / 22

I/O Streams The Character Stream Classes BufferedReader BufferedWriter CharArrayReader CharArrayWriter FileReader FileWriter FilterReader FilterWriter InputStreamReader LineNumberReader OutputStreamWriter PipedReader PipedWriter PrintWriter PushBackReader Reader StringReader StringWriter Writer Buffered input character stream Buffered output character stream Reads from a character array Writes to a character array Reads from a file Writes to a file Filtered reader Filtered writer Translates bytes to characters Counts lines Translates characters to bytes Input pipe Output pipe Contains print() and println() Allows characters to be returned to the input stream Abstract class Reads from a string Writes to a string Abstract class Kizito (Makerere University) CSC 1214 May, 2017 9 / 22

I/O Streams java.io.reader Kizito (Makerere University) CSC 1214 May, 2017 10 / 22

Predefined Streams Java I/O Predefined Streams The java.lang package defines a class called System which contains three predefined stream variables: in, out, and err They are defined as public and static so they can be used by any other part of your program without reference to a specific System object System.out refers to the standard output stream (default: console) System.err refers to the standard error stream (default: console) These streams may be redirected to any compatible I/O devices System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream We have seen sample uses of System.out in previous examples We have also seen a Console class that makes use of System.in Kizito (Makerere University) CSC 1214 May, 2017 11 / 22

Predefined Streams Predefined Streams java.util.scanner Declaration public final class Scanner extends Object implements Iterator<String>, Closeable Constructors 1 Scanner(File source) 2 Scanner(File source, String charsetname) 3 Scanner(InputStream source) 4 Scanner(InputStream source, String charsetname) 5 Scanner(Readable source) 6 Scanner(ReadableByteChannel source) 7 Scanner(ReadableByteChannel source, String charsetname) 8 Scanner(String source) Kizito (Makerere University) CSC 1214 May, 2017 12 / 22

Predefined Streams Predefined Streams java.util.scanner methods Defines over 50 methods nextx() methods: 1 String next() 2 String next(pattern pattern) 3 String next(string pattern) 4 BigDecimal nextbigdecimal() 5 BigInteger nextbiginteger() 6 BigInteger nextbiginteger(int radix) 7 boolean nextboolean() 8 byte nextbyte() 9 byte nextbyte(int radix) 10 double nextdouble() 11 float nextfloat() 12 int nextint() 13 int nextint(int radix) 14 String nextline() 15 long nextlong() 16 long nextlong(int rad) 17 short nextshort() 18 short nextshort(int radix) Kizito (Makerere University) CSC 1214 May, 2017 13 / 22

Console I/O Java I/O Reading Console Input To obtain a stream that is attached to the console, we use the following constructor: BufferedReader(Reader ireader) For example BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); In this case, br is a character-based stream that is linked to the console through System.in Kizito (Makerere University) CSC 1214 May, 2017 14 / 22

Console I/O Reading Console Input BufferedReader Example 1. import java.io.*; 2. 3. class BRRead { 4. public static void main(string args[]) 5. throws IOException { 6. char c; 7. InputStreamReader sr = new InputStreamReader(System.in); 8. BufferedReader br = new BufferedReader(sr); 9. System.out.println("Enter characters, q to quit."); 10. // read characters 11. do { 12. c = (char) br.read(); 13. System.out.println(c); 14. } while(c!= q ); 15. } 16. } Sample output Enter characters, q to quit. 12abcq 1 2 a b c q Kizito (Makerere University) CSC 1214 May, 2017 15 / 22

Console I/O Reading Console Input BufferedReader Example 1. import java.io.*; 2. 3. class BRRead { 4. public static void main(string args[]) 5. throws IOException { 6. char c; 7. InputStreamReader sr = new InputStreamReader(System.in); 8. BufferedReader br = new BufferedReader(sr); 9. System.out.println("Enter characters, q to quit."); 10. // read characters 11. do { 12. c = (char) br.read(); 13. System.out.println(c); 14. } while(c!= q ); 15. } 16. } Sample output Enter characters, q to quit. 12abcq 1 2 a b c q Kizito (Makerere University) CSC 1214 May, 2017 15 / 22

Console I/O Reading characters Reading Console Input Reading Characters and Strings To read a character from BufferedReader, use read(): int read() throws IOException read() reads a character from the input stream and returns it as an integer value. -1 when the end of stream is encountered Reading strings To read a string, use the version of readline() that is a member of the BufferedReader class: String readline() throws IOException For example BufferedReader br = new BufferedReder( new InputStreamReader(System.in)); String str = br.readline(); Kizito (Makerere University) CSC 1214 May, 2017 16 / 22

Console I/O Java I/O Writing Console Output Use methods print(), println(), and write() defined by PrintStream (a type of object referenced by System.out) Example: class WriteDemo { public static void main(string args[]) { int b = A ; } } System.out.write(b); System.out.write( \n ); System.out.println("A string"); Kizito (Makerere University) CSC 1214 May, 2017 17 / 22

Console I/O Java I/O The PrintWriter class PrintWriter defines several constructors. E.g., PrintWriter(OutputStream os, boolean flushonnewline) flushonnewline controls whether Java flushes the output stream every time a new line ( \n ) character is output PrintWriter supports the print() and println() methods PrintWriter Example 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); } } Output This is a string -7 4.5E-7 Kizito (Makerere University) CSC 1214 May, 2017 18 / 22

Console I/O Java I/O The PrintWriter class PrintWriter defines several constructors. E.g., PrintWriter(OutputStream os, boolean flushonnewline) flushonnewline controls whether Java flushes the output stream every time a new line ( \n ) character is output PrintWriter supports the print() and println() methods PrintWriter Example 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); } } Output This is a string -7 4.5E-7 Kizito (Makerere University) CSC 1214 May, 2017 18 / 22

Console I/O Java I/O The PrintWriter class PrintWriter defines several constructors. E.g., PrintWriter(OutputStream os, boolean flushonnewline) flushonnewline controls whether Java flushes the output stream every time a new line ( \n ) character is output PrintWriter supports the print() and println() methods PrintWriter Example 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); } } Output This is a string -7 4.5E-7 Kizito (Makerere University) CSC 1214 May, 2017 18 / 22

File I/O Java I/O Reading and Writing Files Two of the most often-used streams are: 1 FileInputStream(String filename) throws FileNotFoundException 2 FileOutputStream(String filename) throws FileNotFoundException When done with a file, close it using close() defined by both FileInputStream and FileOutputStream To read, use read() defined by FileInputStream To write, use write() defined by FileOutputStream Kizito (Makerere University) CSC 1214 May, 2017 19 / 22

File I/O Reading Example 1. import java.io.*; 2. 3. class ShowFile { 4. public static void main(string args[]) throws IOException { 5. int i; 6. FileInputStream fin; 7. 8. try { 9. fin = new FileInputStream(args[0]); 10. } catch(filenotfoundexception e) { 11. System.out.println("File Not Found"); 12. return; 13. } catch(arrayindexoutofboundsexception e) { 14. System.out.println("Usage: ShowFile File"); 15. return; 16. } 17. do { // read characters until EOF is encountered 18. i = fin.read(); 19. if(i!= -1) System.out.print((char) i); 20. } while(i!= -1); 21. fin.close(); 22. } 23. } Kizito (Makerere University) CSC 1214 May, 2017 20 / 22

File I/O Reading and Writing (Copy) Example 1. import java.io.*; 2. class CopyFile { 3. public static void main(string args[]) throws IOException { 4. int i; 5. FileInputStream fin; 6. FileOutputStream fout; 7. try { 8. try { fin = new FileInputStream(args[0]); // open input file 9. } catch(filenotfoundexception e) { 10. System.out.println("Input File Not Found"); 11. return; 12. } 13. try { fout = new FileOutputStream(args[1]); } // open output file 14. catch(filenotfoundexception e) { 15. System.out.println("Error Opening Output File"); 16. return; 17. } 18. } catch(arrayindexoutofboundsexception e) { 19. System.out.println("Usage: CopyFile From To"); 20. return; 21. } 22. try { // Copy File 23. do { 24. i = fin.read(); 25. if(i!= -1) fout.write(i); 26. } while(i!= -1); 27. } catch(ioexception e) { System.out.println("File Error"); } 28. fin.close(); 29. fout.close(); 30. } 31. } Kizito (Makerere University) CSC 1214 May, 2017 21 / 22

File I/O Modify File Contents 1. import java.util.*; 2. import java.io.*; 3. 4. class FileReplace { 5. public static void main(string args[]) { 6. ArrayList<String> lines = new ArrayList<String>(); 7. try { 8. File f = new File(args[0]); 9. BufferedReader br = new BufferedReader(new FileReader(f)); 10. for (String line; (line = br.readline())!= null; ) { 11. if (line.contains("java")) // line to modify 12. line = line.replace("java", "C"); 13. lines.add(line); 14. } 15. br.close(); 16. 17. PrintStream ps = new PrintStream(f); // open for writing 18. for (Iterator i = lines.iterator(); i.hasnext(); ) 19. ps.println(i.next()); 20. ps.close(); 21. } catch (Exception ex) { ex.printstacktrace(); } 22. } 23. } Kizito (Makerere University) CSC 1214 May, 2017 22 / 22