Download presentation
Presentation is loading. Please wait.
1
Input and Output Streams – part I
2
Lesson Overview Topics covered What are streams?
File types – textual vs. binary data Reading/Writing input from the user File and Formatter classes printf
3
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, ...
4
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
5
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
6
Plumbing Pitstop – where does my water come from???
Reservoir Main Pipe Sec. Pipe Filter
7
Plumbing Pitstop – Getting Water ≡ Reading
Reservoir Main Pipe Sec. Pipe Filter File (Source) FileInputStream DataInputStream
8
Plumbing Pitstop – where does my used water go to?
Sink (Drain) Source Pipe Filter Dest. Pipe Destination Nachal Soreq?
9
Plumbing Pitstop – Spilling Water ≡ Writing
File ByteArrayOutputStream Destination Sink (Drain) Source Pipe Filter Dest. Pipe BufferedOutputStream ByteArray byte[] arr; FileOutputStream
10
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.
11
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:
12
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
13
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. Input stream reading direction writing direction Output stream
14
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
15
Basic reading/writing algorithms
(1) open a stream (2) while (more information) (2.1) write information (3) close the stream
16
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.
17
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.
18
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.
19
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.
20
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
21
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.
22
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.
23
Byte Streams Subclasses of InputStream and OutputStream provide specialized I/O that falls into two categories
24
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)
25
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.
26
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)
27
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.
28
Stream Overview
29
Stream Overview (cont.)
30
Stream Overview (cont.)
31
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!"); }
32
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.
33
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(); }
34
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.
35
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() ...
36
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() );
37
//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
38
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>*)
39
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.
40
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)
41
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)
42
printf examples Outputs: '12 35.500'
System.out.printf(“%d\t%2.3f\n”,12, ); Outputs: ' ' 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!
43
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)
44
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”)); }
45
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).
46
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;
47
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)"
48
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;
49
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
50
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.