Sie sind auf Seite 1von 58

J2SE Core Java

PG-DESD Aug -2013

Session 7:
Learning Objectives

Explain Java IO

Describe Streams
Byte / Character Text /Character

Those Scary Stream Classes


Most programmers are taken aback by the complexity of the stream classes
There are many classes in the java.io package The applicability of each class is not always obvious

What are Streams?


The I/O System in Java is based on Streams
Input Streams are data sources Programmers read data from input streams Output Streams are data sinks Programmers write data to output streams

Java has two main types of Streams


Byte Oriented Each datum is a byte uses InputStream class hierarchy & OutputStream class hierarchy Character-based I/O streams each datum is a Unicode character uses Reader class hierarchy & Writer class hierarchy

Streams
A stream is a ordered sequence of bytes that can be used as
A source for input (input stream) A destination for output (output stream)

A program can have multiple streams


Examples: console, files, sockets, memory, strings

The java classes in the package java.io provide utilities for dealing with streams

Overview of I/O Streams


To bring in information, a program opens a stream on an information source (a file, memory, a socket) and reads the information sequentially, as shown in the following figure.

Overview of I/O STREAMS


Similarly, a program can send information to an external destination by opening a stream to a destination and writing the information out sequentially, as shown in the following figure.

Overview of I/O streams


The java.io package contains a collection of stream classes that support 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 i.e Character Stream and Byte Stream
Java has predefined byte streams: System.in System.out System.err

I/O Streams
Usual Purpose: storing data to nonvolatile devices, e.g. Hard disk Classes provided by package java.io Data is transferred to devices by streams

output - stream Program input - stream Program Device Device

I/O Streams
JAVA distinguishes between 2 types of streams:

Text streams, containing characters


I M A S T R I N G \n
Device

Program

Binary Streams, containing 8 bit information


Program 01101001 11101101 00000000 Device

Streams
Streams in JAVA are Objects, of course! Having 2 types of streams (text / binary) and 2 directions (input / output) 1. 2. 3. 4. Results in 4 base-classes dealing with I/O: Reader: text-input Writer: text-output InputStream: byte-input OutputStream: byte-output

Streams
InputStream

OutputStream
binary

Reader

text

Writer

Streams
InputStream, OutputStream, Reader, Writer are abstract classes Subclasses can be classified by 2 different characteristics of sources / destinations: For final device (data sink stream) purpose: serve as the source/destination of the stream
(these streams really write or read !)

for intermediate process (processing stream) Purpose: alters or manages information in the stream
(these streams are luxury additions, offering methods for convenient or more efficient stream-handling)

Character Streams
Reader and Writer are the abstract super classes
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
The following figure shows the class hierarchies for the Reader and Writer classes.

Character Streams
The following figure shows the class hierarchies for the Reader and Writer classes.

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.

Two of the byte stream classes, ObjectInputStream and ObjectOutputStream, are used for object serialization.

Byte Streams
The class hierarchy for the InputStream Class

Byte Stream
Class hierarchy figure for OutputStream Class

I/O: General Scheme

In General:
Reading (writing): open an input (output) stream while there is more information read(write) next data from the stream close the stream.

In JAVA:
Create a stream object and associate it with a disk-file Give the stream object the desired functionality while there is more information read(write) next data from (to) the stream close the stream.

Example
Writing a textfile:

Create a stream object and associate it with a disk-file Give the stream object the desired functionality write data to the stream close the stream.

Writing Textfiles
Class: FileWriter Frequently used methods:

Writing Textfiles
Using FileWriter It is not very convenient is not efficient (every character is written in a single step, invoking a huge overhead) Better: wrap FileWriter with processing streams BufferedWriter PrintWriter

Wrapping Textfiles
BufferedWriter: Buffers output of FileWriter, i.e. multiple characters are processed together, enhancing efficiency PrintWriter provides methods for convenient handling, e.g. println()
( remark: the System.out.println() method is a method of the PrintWriter-instance System.out ! )

Wrapping a Writer
A typical code segment for opening a convenient, efficient textfile:
FileWriter out = new FileWriter("test.txt"); BufferedWriter b = new BufferedWriter(out); PrintWriter p = new PrintWriter(b);

Or with anonymous (unnamed) objects:


PrintWriter p = new PrintWriter(new BufferedWriter( new FileWriter("test.txt")));

Reading Textfiles
Class: FileReader Frequently used Methods:

(The other methods are used for positioning)

Wrapping a Reader

Using FileReader is not very efficient. Better wrap it with BufferedReader: BufferedReader br =new BufferedReader( new FileReader(name));
Remark: BufferedReader contains the method readLine(), which is convenient for reading textfiles

EOF Detection
Detecting the end of a file (EOF): Usually amount of data to be read is not known Reading methods return impossible value if end of file is reached Example: FileReader.read returns -1 BufferedReader.readLine() returns null Typical code for EOF detection: while ((c = myReader.read() != -1){ // read and check c ...do something with c }

Example
import java.io.*; public class IOTest1 { public static void main(String[] args) { try{ BufferedReader myInput = new BufferedReader(new FileReader("IOTest1.java")); BufferedWriter myOutput = new BufferedWriter(new FileWriter("Test1.txt")); int c; while ((c=myInput.read()) != -1) myOutput.write(c);

myInput.close(); myOutput.close(); }catch(IOException e){}


} }

import java.util.*; The scanner class import java.io.File; import java.io.FileNotFoundException; public class scanIn { public static void main(String[] args) { String first, last; int ssn; try{ Scanner sc = new Scanner(new File("input.txt")); while (sc.hasNext()) { first = sc.next(); last = sc.next(); ssn = sc.nextInt(); System.out.println("First: " + first + "\nLast: " + last + "\nSSN: " + ssn); } }catch (FileNotFoundException e){ System.out.println(e); } //end catch } //end main } // end class

DataInputStream
/*Example using DataInputStream.*/ import java.io.DataInputStream; public class InputOutput { public static void main(String[] as) { try { DataInputStream dis = new DataInputStream(System.in); System.out.println("Enter First Number"); int a =Integer.parseInt(dis.readLine()); System.out.println("Enter Second Number"); int b = Integer.parseInt(dis.readLine()); int sum = a+b; System.out.println("Sum is "+sum); } catch (Exception e) { e.printStackTrace(); } } }
Output: Enter First Number 2 Enter Second Number 4 Sum is 6

Binary vs. TextFiles


pro con

Binary

Efficient in terms of Pre information about data needed time and space
to understand content

Text

Human readable, Not efficient contains redundant information

Das könnte Ihnen auch gefallen