Java I/O Input: information brought to program from an external source

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
1 Streams and Input/Output Files Part I. 2 Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses.
Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
III. Streams. Introduction Often a program needs to bring in information from an external source or to send out information to an external destination.
Standard input, output and error. Lecture Under Construction.
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
Java I/O and Java Networking (Client Side) Yoshi.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Algorithm Programming I/O via Java Streams Bar-Ilan University תשס"ח by Moshe Fresko.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
CIS 068 JAVA I/O: Streams and Files. CIS 068 I/O Usual Purpose: storing data to ‘nonvolatile‘ devices, e.g. harddisk Classes provided by package java.io.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
Copyright © Curt Hill Java I/O Flexibility and Layering.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
I / O in java. java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader.
I/O in Java Dennis Burford
The Java I/O Classes and Interfaces cont’d
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
Two Ways to Store Data in a File  Text format  Binary format.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
Lecture 5 I/O and Parsing
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
DEPARTMENT OF COMPUTER SCIENCE N.HARIKA. Contents Overview of I/O Streams Character Streams Byte Streams Using the Streams 2.
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Java I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Java IO Exploring the java.io package and living to talk about it.
java.io supports console and file I/O
The Java IO System Different kinds of IO Different kinds of operations
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
Exception Handling, Reading and Writing in Files, Serialization,
OO Design and Programming II I/O: Reading and Writing
Ch14 Files and Streams OBJECTIVES
12: The Java I/O System stream model.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
I/O Streams- Basics Byte Streams and Character Streams
CSC 143 Java Streams.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Web Design & Development Lecture 8
David Davenport Spring 2005
Presentation transcript:

Java I/O Input: information brought to program from an external source Output: information sent from program to an external destination External source or destination can be: Disk file or memory Another program (piping) Network location (URL) Information type can be: Primitive types or objects Images or sounds

I/O Streams A stream is a data structure facilitating handling of an information source for sequential access Source reads Program Stream Program writes Destination Programs read from and write to streams, and not the actual source or destination

Standard Input and Output Streams Java provides references to the standard input stream (keyboard) and standard output stream (display) System.in: an instance of the standard Java Platform InputStream class System.out: an instance of the PrintStream class InputStream and PrintStream are in the java.io package

InputStream Class An input stream provides 8-bit bytes. The InputStream class is a direct descendant of the Object class. The shaded subclasses implement data sink streams; unshaded subclasses implement processing streams.

Input Streams Used for Processing InputStream: abstract superclass of all input stream classes All subclasses of InputStream must implement read() method that returns one byte as an int: FilterInputStream: designed to be extended to provide extra functionality involving the transformation (filtering) of data SequenceInputStream: concatenates several streams into one logical stream ObjectInputStream: reads data and objects that have been serialized to an output destination

Subclasses of FilterInputStream DataInputStream: reads bytes that are parts of primitive types (int, double, etc.) and returns a specific value. BufferedInputStream: buffers input bytes for efficiency PushbackInputStream: adds the ability to ``push back'' or ``unread'' one byte LineNumberInputStream: deprecated. Use LineNumberReader class instead

Input Streams Used on Data Sinks (all subclasses of InputStream) FileInputStream: obtains input bytes from a file in a file system (intended for raw data, as for image files, only) PipedInputStream: gets bytes from a piped output stream, usually from another program thread ByteArrayInputStream: gets bytes from an internal buffer which is a byte array StringBufferInputStream: deprecated. Use StringReader class instead

OutputStream Class An output stream outputs 8-bit bytes. The OutputStream class is a direct descendant of the Object class. The shaded subclasses implement data sink streams; unshaded subclasses implement processing streams.

Output Streams Used for Processing OutputStream: abstract superclass of all output stream classes All subclasses of OutputStream must implement write() method that writes one byte stored as an int: FilterOutputStream: designed to be extended to provide extra functionality involving the transformation (filtering) of data ObjectOutputStream: writes data and objects that have been serialized to an output destination

Subclasses of FilterOutputStream DataOutputStream: writes primitive data types (int, double, etc.) BufferedOutputStream: buffers output bytes for efficiency PrintStream: converts primitive data types to string representation for printing can be created to perform automatic flushing

Output Streams Used on Data Sinks (all subclasses of OutputStream) FileOutputStream: sends output bytes to a file in a file system (intended for raw data, as for image files, only) PipedOutputStream: sends bytes to a piped input stream, usually from another program thread ByteArrayOutputStream: sends bytes to an internal buffer which is a byte array

Example: Echoing Bytes from Standard Input to Standard Output import java.io.*; public class Echo { public static void main(String[] args) throws IOException { int c; while ((c = System.in.read()) != -1) System.out.write(c); }

Notes on the Example Must import the I/O package, of which all the input and output stream classes are part Since the read() method may encounter an I/O error, the main() method must either: catch and deal with an IOException, or throw the IOException to the calling procedure Even though the streams read and write bytes, the internal storage is an int The read() method returns -1 if EOF is encountered

Example Output Output is in red: 82% javac Echo.java 83% java Echo now is the time[Return] now is the time for all good men[Return] for all good men to come to the aid[Return] to come to the aid [ctl-D] 84%

Unix Redirection 84% java Echo > myfile now is the time for all good men to come to the aid [ctl-D] 85% cat myfile 86% java Echo < myfile > newfile 87% cat newfile forall good men 88%

Streams vs. Readers/Writers The InputStream and OutputStream methods work on bytes The Echo example notwithstanding, the stream classes are used primarily for binary data as in sound and images In Java, characters are represented using 16-bit Unicode To insure internationalization, programs dealing with character I/O should use descendants of the Reader and Writer classes

Readers Think of the Reader class like InputStream that has been specialized to deal with characters. Reader is a direct, abstract subclass of Object. Note similarity to the InputStream hierarchy.

Writers Think of the Writer class like OutputStream that has been specialized to deal with characters. Writer is a direct, abstract subclass of Object. Note similarity to the OutputStream hierarchy.

New Echo Class import java.io.*; public class Echo { public static void main(String[] args) throws IOException { InputStreamReader r = new InputStreamReader(System.in); OutputStreamWriter w = new OutputStreamWriter(System.out); int c; while ((c = r.read()) != -1) w.write(c); w.flush(); }

Notes on the New Echo Class InputStreamReader and OutputStreamWriter are built on top of InputStream and OutputStream so their constructors require streams as arguments Internal character storage is an int Processing loop is exactly the same as for streams The writer requires flushing

New Echo Example Output Output is in red: 93% java Echo now is the time[Return] for all good men[Return] to come to the aid[Return] [ctl-D] now is the time for all good men to come to the aid 94%

File Handling Example import java.io.*; public class FileCopy { public static void main(String[] args) throws IOException { FileReader r = new FileReader("infile"); FileWriter w = new FileWriter("outfile"); int c; while ((c = r.read()) != -1) w.write(c); w.flush(); }

Notes on FileCopy FileReader and FileWriter constructors can take file names as strings for arguments Processing loop and flush call the same as before This class is of limited use since the file names are hard coded

FileCopy Example Output 105% ls FileCopy.class FileCopy.java infile 106% cat infile Here is a test file to show that the FileCopy class really works. 107% java FileCopy 108% ls outfile 109% cat outfile 110%

Exception Example Note: The FileNotFoundException class is a 111% rm outfile 112% rm infile 113% ls FileCopy.class FileCopy.java 114% java FileCopy Exception in thread "main" java.io.FileNotFoundException: infile (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:103) at java.io.FileInputStream.<init>(FileInputStream.java:66) at java.io.FileReader.<init>(FileReader.java:39) at FileCopy.main(FileCopy.java:7) 115% Note: The FileNotFoundException class is a subclass of IOException. The exception generates a stack trace with line numbers of offending code.

Reading Strings The BufferedReader class has a readLine() method for reading strings import java.io.*; public class FileCopy { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Source file name: "); String inFileName = br.readLine(); System.out.print("Destination file name: "); String outFileName = br.readLine(); FileReader r = new FileReader(inFileName); FileWriter w = new FileWriter(outFileName); int c; while ((c = r.read()) != -1) w.write(c); w.flush(); }

Example Output 121% ls FileCopy.class FileCopy.java 122% java FileCopy Source file name: FileCopy.java Destination file name: X.java 123% ls FileCopy.class FileCopy.java X.java 124% cat X.java import java.io.*; public class FileCopy { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Source file name: "); String inFileName = br.readLine(); System.out.print("Destination file name: "); String outFileName = br.readLine(); ... }

Reading Strings and Converting to Numbers The java.lang package has classes Integer, Double, etc., whose instances have int, double, etc. as data members These classes have static methods for converting strings to numbers For example, the Integer class has a parseInt(<string>) method that returns an int given a String Similarly, the Double class has a parseDouble(<string>) method that returns a double

Example import java.io.*; public class ConvertTest { public static void main(String[] args) throws IOException { int sum = 0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter an integer: "); String s = br.readLine(); while ( s != null ) { int num = Integer.parseInt(s); sum += num; s = br.readLine(); } System.out.println("The sum is " + sum);

Notes on the Example The readLine() method returns a null string if end of stream is reached The parseInt() method must be fully qualified with its class name since the method is static The parseInt() method might throw a NumberFormatException if its argument is not syntactically correct Unlike an IOException, a NumberFormatException is not checked by the compiler

Example Output 136% java ConvertTest Enter an integer: 3 Enter an integer: [ctl-D] The sum is 1683 137% java ConvertTest Enter an integer: trash Exception in thread "main" java.lang.NumberFormatException: trash at java.lang.Integer.parseInt(Integer.java:426) at java.lang.Integer.parseInt(Integer.java:476) at ConvertTest.main(ConvertTest.java:12) 138%

Lining Output Up in Columns import java.io.*; public class ColumnTest { public static void main(String[] args) throws IOException { int sum = 0; int[] nums = new int[10]; int i = 0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter an integer: "); String s = br.readLine(); while ( s != null ) { nums[i] = Integer.parseInt(s); sum += nums[i++]; s = br.readLine(); } System.out.println("Numbers"); System.out.println("-------"); for (int j = 0; j < i; j++) System.out.println(nums[j]); System.out.println(sum + " total");

Output 144% java ColumnTest Enter an integer: 3 Enter an integer: 417 Enter an integer: [ctl-D] Numbers ------- 3 417 29 1234 1683 total 145%

Decimal Formatting The java.text package has a DecimalFormat class for formatting decimals as strings The DecimalFormat class has a format() method that takes an integer and formats it according to a pattern string given to the DecimalFormat object's constructor The pattern string can have regular characters as well as special formatting characters The special character ``0'' indicates a decimal digit E.g. the pattern string `` 0000'' indicates a string with three leading blanks then an integer in 4-digit field

Decimal Formatting Example import java.io.*; import java.text.*; public class ColumnTest { public static void main(String[] args) throws IOException { int sum = 0; int[] nums = new int[10]; int i = 0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter an integer: "); String s = br.readLine(); while ( s != null ) { nums[i] = Integer.parseInt(s); sum += nums[i++]; s = br.readLine(); } DecimalFormat f = new DecimalFormat(" 0000"); System.out.println("Numbers"); System.out.println("-------"); for (int j = 0; j < i; j++) System.out.println(f.format(nums[j])); System.out.println(f.format(sum) + " total");

Decimal Formatting Example Output 144% java ColumnTest Enter an integer: 3 Enter an integer: 417 Enter an integer: 29 Enter an integer: 1234 Enter an integer: [ctl-D] Numbers ------- 0003 0417 0029 1234 1683 total 145% If you can figure out how to get the leading zeros to print as blanks, please let me know.