Input and Output Streams – part I

Slides:



Advertisements
Similar presentations
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.
Advertisements

Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
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.
 2005 Pearson Education, Inc. All rights reserved Introduction.
Standard input, output and error. Lecture Under Construction.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
Overview of Java I/O. Stream A Program often needs to read/write information from/to outer source/destination. Outer source/destination can be : –A File.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
פיתוח מונחה עצמים – שפת JAVA קבצים. References קורס "שיטות בהנדסת תוכנה", הפקולטה למדעי המחשב, הטכניון. קורס "מערכות מידע מבוזרות", הפקולטה להנדסת תעשייה.
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
 Pearson Education, Inc. All rights reserved Formatted Output.
 2005 Pearson Education, Inc. All rights reserved Formatted Output.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
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.
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.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
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.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
 Pearson Education, Inc. All rights reserved Files and Streams.
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.
Chapter - 11 Introduction to File and Streams This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects.
DEPARTMENT OF COMPUTER SCIENCE N.HARIKA. Contents Overview of I/O Streams Character Streams Byte Streams Using the Streams 2.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Generics and file handling Presented by: Abha Kumari Neha Pradip Vhanmane Raj Visa Rashmi Kewlani Suvrat Dixit.
Java IO Exploring the java.io package and living to talk about it.
Chapter 10: I/O Streams Input Streams Output Streams
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Sequential files creation & writing
IO in java.
28 Formatted Output.
OO Design and Programming II I/O: Reading and Writing
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Object Writing in files
Streams and File I/O.
University of Central Florida COP 3330 Object Oriented Programming
12: The Java I/O System stream model.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Programming in Java Files and I/O Streams
CSS161: Fundamentals of Computing
Formatting Output.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
Streams and File I/O Chapter 14.
Chapter 17 – Files and Streams
Input and Output Stream
Introduction to Java Applications
Files and Streams in Java
Web Design & Development Lecture 8
Chapter 15 Files, Streams and Object Serialization
Java Chapter 2 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Input and Output Streams – part I

Lesson Overview Topics covered What are streams? File types – textual vs. binary data Reading/Writing input from the user File and Formatter classes printf

The General Scenario There are many types of input sources: Reading a file from a local disk / diskette Receiving a web page from a remote server Receiving a communication message through a network. Receiving a signal from a sensor of a robot Scanner, video camera, ...

The General Scenario Similarly, there are many types of output destinations: Writing to a file on a local disk / diskette Sending query information to a remote web server Sending communication message to a remote host. Sending a command to a robot controller. Printing a document to a printer / fax Displaying graphics on the screen

The General Scenario Application Problem : How can we communicate with various devices using a single common interface? Notice that we do not want to know the details of the hardware devices. Instead we would like to have a common interface for accessing all of them them! Application

Plumbing Pitstop – where does my water come from??? Reservoir Main Pipe Sec. Pipe Filter

Plumbing Pitstop – Getting Water ≡ Reading Reservoir Main Pipe Sec. Pipe Filter File (Source) FileInputStream DataInputStream

Plumbing Pitstop – where does my used water go to? Sink (Drain) Source Pipe Filter Dest. Pipe Destination Nachal Soreq?

Plumbing Pitstop – Spilling Water ≡ Writing File ByteArrayOutputStream Destination Sink (Drain) Source Pipe Filter Dest. Pipe BufferedOutputStream ByteArray byte[] arr; FileOutputStream

I/O Abstraction We can achieve the separation by designing a common interface for reading any kind of data, and common interface for writing any kind of data. This interface is implemented by the notion of input and output streams. Any input/output can be represented as a sequence of bits. For convenience we divide the sequence into a sequence of bytes.

Input/Output Streams Bringing in information (reading) is done by opening a stream on an information source (a file, memory, a socket) and reading the information sequentially:

Input/Output Streams Sending information (writing) to an external destination is done by opening a stream to a destination and writing the information out sequentially

Input/Output Streams Input stream Output stream reading direction An input/output stream is a sequence of bytes that is attached to some input/output source. You can read/write data from/to the stream in a sequential order. One byte at a time or several bytes at a time. 12 72 32 17 83 11 7 91 108 43 55 31 37 34 13 17 1 15 Input stream reading direction writing direction Output stream

Basic reading/writing algorithms No matter where the data is coming from or going to and no matter what its type, the algorithms for sequentially reading and writing data are basically the same: Reading : (1) open a stream (2) while (more information) (2.1) read information (3) close the stream

Basic reading/writing algorithms (1) open a stream (2) while (more information) (2.1) write information (3) close the stream

Input Output Streams in Java The java.io package contains a collection of stream classes that support these algorithms for reading and writing. To use these classes, a program needs to import the java.io package. The stream classes are divided into two class hierarchies, based on the data type (either characters or bytes) on which they operate.

Textual vs. Binary Data We often make a distinction between textual data and other kinds of data We refer to files that stores text as ‘text files’ and to other files as ‘binary files’. Binary files stores their information in various formats. In order to understand the content of a binary file you need to have a viewer that knows how to read the format the file is written with. The structure of text files is more simple. It uses an encoding that gives a numeric code for each symbol and the text is stored as a list of numbers.

Textual vs. Binary Data Java makes a distinction between textual data and binary data. This distinction comes to bridge the gap between the non-standard representation of text by the operating system and the standard unicode representation of text in Java. Java defines a parallel set of classes for reading/writing textual data.

Character Streams Reader and Writer are the abstract superclasses for character streams in java.io. Reader provides the API and partial implementation for readers — streams that read 16-bit characters. Writer provides the API and partial implementation for writers — streams that write 16-bit characters.

Character Streams Subclasses of Reader and Writer implement specialized streams and are divided into two categories: those that read from or write to data sinks and those that perform some sort of processing . data sinks processing

Character Streams Most programs should use readers and writers to read and write textual information. Why? The reason is that they can handle any character in the Unicode character set, whereas the byte streams are limited to ISO-Latin-1 8-bit bytes.

Byte Streams To read and write 8-bit bytes, programs should use the byte streams, descendents of InputStream and OutputStream. InputStream and OutputStream provide the API and partial implementation for input streams (streams that read 8-bit bytes) and output streams (streams that write 8-bit bytes). These streams are typically used to read and write binary data such as images and sounds.

Byte Streams Subclasses of InputStream and OutputStream provide specialized I/O that falls into two categories

Input Superclasses Reader and InputStream define similar APIs but for different data types. Both are abstract classes! Reader contains these methods for reading characters and arrays of characters. int read() //Read a single character,-1 is ends. int read(char cbuf[]) //Read chars into an array //read chars into a portion of the array. int read(char cbuf[], int offset, int length)

Input Superclasses InputStream defines the same methods but for reading bytes and arrays of bytes: int read() //Read a single byte,-1 if end. int read(byte cbuf[]) //Read several bytes... int read(byte cbuf[], int offset, int length) Both Reader and InputStream provide methods for marking a location in the stream, skipping input, and resetting the current position.

Output Superclasses Writer and OutputStream are similarly parallel. Writer defines these methods for writing characters and arrays of characters: int write(int c) //write a single character. int write(char cbuf[]) //write an array of chars. //write a portion of an array of chars. int write(char cbuf[], int offset, int length)

Output Superclasses OutputStream defines the same methods but for bytes: int write(int c) //writes a single byte int write(byte cbuf[]) //writes an array of bytes int write(byte cbuf[], int offset, int length) All of the streams — readers, writers, input streams, and output streams — are automatically opened when created. Close a stream by calling its close method. A program should close a stream as soon as it is done with it, in order to free up system resources.

Stream Overview

Stream Overview (cont.)

Stream Overview (cont.)

Example 1: Typing a text file import java.io.*; public class MyTextType { public static void main(String[] args){ try{ FileReader fileIn= new FileReader("temp.txt"); int c; while((c=fileIn.read()) != -1) System.out.print((char)c); fileIn.close(); }catch(FileNotFoundException fnfe){ System.err.println("file temp.text not found!!!"); }catch (IOException ioe){ System.err.println("error reading from file!"); }

I/O and Exceptions Almost all I/O operations throw an IOException object in case some problems occur during reading/writing. This is a classical example of where exceptions are useful, since in many cases IO operations can cause unexpected situations. Examples: Trying to read a file which does not exist. Trying to write to a file that is write-protected. Class IOException is the root of the IO exceptions hirerachy – there are many different subclasses: e.g FileNotFoundException.

Example 2: Copying a text file import java.io.*; public class Copy { public static void main(String[] args) throws IOException{ File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }

Example 2: Copying a text file (cont.) Here is the code that the Copy program uses to create a file reader: File inputFile = new File("farrago.txt"); FileReader in = new FileReader(inputFile); This code creates a File object that represents the named file on the native file system. File is a utility class provided by java.io. The Copy program uses this object only to construct a file reader on a file. However, the program could use inputFile to get information, such as its full path name, about the file.

Class File Useful for retrieving information about files or directories from the disk. File objects do not open files and do not provide any file-processing capabilities. Contains various methods to query a file – canRead(), canWrite(), exists(), isFile(), isDirectory(), getPath(), length() ...

import java.io.File; public class FileDemonstration{ public void analyzePath( String path ){ File name = new File( path ); if ( name.exists() ) { System.out.printf( "%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s", name.getName(), " exists", ( name.isFile() ? "is a file" : "is not a file" ), ( name.isDirectory() ? "is a directory" : "is not a directory" ), ( name.isAbsolute() ? "is absolute path" : "is not absolute path" ), "Last modified: ", name.lastModified(), "Length: ", name.length(), "Path: ", name.getPath(), "Absolute path: ", name.getAbsolutePath(), "Parent: ", name.getParent() );

//file continued... if ( name.isDirectory() ) { // output directory listing String directory[] = name.list(); System.out.println( "\n\nDirectory contents:\n" ); for ( String directoryName : directory ) System.out.printf( "%s\n", directoryName ); } } // end outer if else { // not file or directory, output error message System.out.printf( "%s %s", path, "does not exist." ); } // end method analyzePath } // end class FileDemonstration

printf? Java 5.0 has new printing capabilities which are based on the notorious C language printf function. printf is defined in System.out and also in class Formatter (see below). printf general format: printf(<formatString>,<value>*)

The printf format-string The format string describes the output format. Can consists of fixed-text and format-specifiers. Fixed-text is outputed as in System.out.print format-specifiers are placeholders for a value and specify the type of data to output. format-specifiers may also include formatting information. In simple form each format-specifier begins with a percent sign (%) and is followed by a conversion-characater.

The printf format-string (cont.) Basic conversion-characters %d an integer %f a float (%e in exponential notation) %c a character %s a String %b a boolean %% a percent character %n a platform-specific line separator (e.g., \r\n on Windows or \n on UNIX/LINUX systems)

The printf format-string (cont.) Each conversion character can also be enhanced with optional formatting information such as: argument index: e.g, “%4$s” (print fourth argument as String) flags: e.g., “%-d” (minus sign), “%0d” (pad with a zero at beginning of number). field width: e.g., “%4d” (width of 4 digits) precision (rounding): e.g., “%9.3f” (9 digits before the decimal point, 3 after it)

printf examples Outputs: '12 35.500' System.out.printf(“%d\t%2.3f\n”,12,35.4999); Outputs: '12 35.500' int grade = 49; System.out.printf(“%s %s has %s the test\n” Todd,Sod (grade > 50 ? "passed" : "failed")); Outputs: 'Todd Sod has failed the test' Notice the if syntax!

The Scanner class Class Scanner provides an intuitive and simple wrapper that allows to read from any input stream without actually handling streams. Objects of type Scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type. Scanner can be used to read input from the user! - this is the replacement of our SimpleInput class (i.e. SimpleInput – out, Scanner - in)

Scanner example import java.util.Scanner; public class UserInputDemo { public static void main( String args[] ){ Scanner input = new Scanner( System.in ); System.out.printf(“Please Enter your name:”); String name = input.next(); System.out.printf(“\nEnter your age:”); int age = input.nextInt(); System.out.printf(“Your name is %s and you are much too %s for us”, name, (age > 20? “old” : “young”)); }

Scanner comments Notice that no IOException has been handled (why?) Can also hook up to any File object, and on any InputStream in general. Main use if for parsing input using regular expressions (for more details see this week's tirgul).

Formatting output – beyond printf Formatter class - An interpreter for printf-style format strings. Provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale- specific output. Formatted printing for the Java language is heavily inspired by C's printf. Although the format strings are similar to C, some customizations have been made to accommodate the Java language and exploit some of its features. Java formatting is more strict than C's;

Formatter class Formatter can also output its format to any File object, and therefore allows simple text file-writing capabilities Syntax is same as printf: // The '(' numeric flag may be used to format negative // numbers with parentheses rather than a minus sign. formatter.format("Amount gained or lost since last statement: $ %(,.2f",balanceDelta); // -> "Amount gained or lost since last statement:$(6,217.58)"

Formatter Example: // Writing data to a text file with class Formatter. import java.io.FileNotFoundException; import java.lang.SecurityException; import java.util.Formatter; import java.util.FormatterClosedException; import java.util.NoSuchElementException; import java.util.Scanner; public class CreateTextFile { // object used to output text to file private Formatter output;

public void openFile(){ try{ output = new Formatter( "clients.txt" ); } catch ( SecurityException se ){ System.err.println( "You do not have write access to this file." ); System.exit( 1 ); catch(FileNotFoundException fnfe){ System.err.println( "Error creating file." ); } // end method openFile

public void addNames(String[] names){ for (String name : names) try{ output.format(“%s\n”,name); }catch(FormatterClosedException fce) System.err.println("Error writing to file." ); return; } public void closeFile(){ if(output != null) output.close(); } }//end of class