Upload
gauravlko
View
238
Download
0
Embed Size (px)
Citation preview
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
1/58
J2SE Core Java
PG-DESD
Aug -2013
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
2/58
Session 7:
Learning Objectives
Explain Java IO
Describe Streams
Byte / Character Text /Character
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
3/58
Most programmers are taken aback by the complexity of the
stream classesThere are many classes in the java.io packageThe applicability of each class is not always obvious
Those Scary Stream Classes
The I/O System in Java is based on StreamsInput Streams are data sourcesProgrammers read data from input streams
Output Streams are data sinksProgrammers write data to output streams
Java has two main types of StreamsByte OrientedEach datum is a byteuses InputStream class hierarchy & OutputStream class hierarchy
Character-based I/O streamseach datum is a Unicode character
uses Reader class hierarchy & Writer class hierarchy
What are Streams?
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
4/58
Streams
A streamis a ordered sequence of bytes that can beused 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
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
5/58
Overview of I/O Streams
To bring in information, a program opens a
streamon an information source (a file,
memory, a socket) and reads the informationsequentially, as shown in the following figure.
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
6/58
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
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
7/58
Overview of I/O streams
Thejava.io package contains a collection of stream classes
that support algorithms for reading and writing. To use these classes, a program needs to import thejava.io
package.
The stream classes are divided into two class hierarchies,
based on the data type (either characters or bytes) on whichthey operate i.e Character Stream and Byte Stream
Java has predefined bytestreams:
System.in
System.out
System.err
http://java.sun.com/j2se/5.0/docs/api/java/io/package-summary.htmlhttp://java.sun.com/j2se/5.0/docs/api/java/io/package-summary.htmlhttp://java.sun.com/j2se/5.0/docs/api/java/io/package-summary.htmlhttp://java.sun.com/j2se/5.0/docs/api/java/io/package-summary.html8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
8/58
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
Program Device
output - stream
Program Device
input - stream
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
9/58
I/O Streams
JAVA distinguishes between 2 types of streams:
Textstreams, containing characters
I M A S T R I N G \nProgram Device
Binary Streams, containing 8bit information
01101001Program Device11101101 00000000
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
10/58
Streams Streams in JAVA are Objects, of course!
Having 2 types of streams (text / binary) and
2 directions (input / output)
Results in 4 base-classesdealing with I/O:
1. Reader: text-input
2. Writer: text-output3. InputStream: byte-input
4. OutputStream: byte-output
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
11/58
Streams InputStream
OutputStream
Reader
Writer
binary
text
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
12/58
Streams
InputStream, OutputStream, Reader, Writer are abstract
classes
Subclasses can be classified by 2 different characteristics ofsources / 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)
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
13/58
Character Streams
Reader and Writer are the abstract super classesfor character streams in java.io.
Readerprovides the API and partial implementation
for readers ( streams that read 16-bit characters )
Writerprovides the API and partial implementation
for writers ( streams that write 16-bit characters).
http://java.sun.com/j2se/5.0/docs/api/java/io/Reader.htmlhttp://java.sun.com/j2se/5.0/docs/api/java/io/Writer.htmlhttp://java.sun.com/j2se/5.0/docs/api/java/io/Writer.htmlhttp://java.sun.com/j2se/5.0/docs/api/java/io/Reader.html8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
14/58
Character Streams
The following figure shows the class hierarchies for
the Reader and Writerclasses.
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
15/58
Character Streams
The following figure shows the class hierarchies forthe Readerand Writer classes.
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
16/58
Byte Streams
To read and write 8-bit bytes, programs should use the bytestreams, descendents of InputStream and OutputStream .
InputStreamand OutputStreamprovide the API and partialimplementation for input streams (streams that read 8-bitbytes) and output streams (streams that write 8-bit bytes).
These streams are typically used to read and write binary datasuch as images and sounds.
Two of the byte stream classes, ObjectInputStream andObjectOutputStream, are used for object serialization.
http://java.sun.com/j2se/5.0/docs/api/java/io/InputStream.htmlhttp://java.sun.com/j2se/5.0/docs/api/java/io/OutputStream.htmlhttp://java.sun.com/j2se/5.0/docs/api/java/io/OutputStream.htmlhttp://java.sun.com/j2se/5.0/docs/api/java/io/InputStream.html8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
17/58
Byte Streams
The class hierarchy for the InputStream Class
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
18/58
Byte Stream
Class hierarchy figure for OutputStreamClass
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
19/58
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 objectand associate it with adisk-file
Give the stream objectthe desired functionality
while there is more information
read(write) next data from (to) the stream
close the stream.
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
20/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
21/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
22/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
23/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
24/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
25/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
26/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
27/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
28/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
29/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
30/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
31/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
32/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
33/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
34/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
35/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
36/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
37/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
38/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
39/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
40/58
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.
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
41/58
Writing Textfiles
Class: FileWriter
Frequently used methods:
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
42/58
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
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
43/58
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 ! )
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
44/58
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= newPrintWriter(newBufferedWriter(
newFileWriter("test.txt")));
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
45/58
Reading Textfiles
Class: FileReader
Frequently used Methods:
(The other methods are used for
positioning)
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
46/58
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
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
47/58
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 andcheck c
...do something with c
}
E l
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
48/58
Example import java.io.*;
public class IOTest1
{
public static void main(String[] args)
{
try{
BufferedReader myInput = new BufferedReader(newFileReader("IOTest1.java"));
BufferedWriter myOutput = new BufferedWriter(newFileWriter("Test1.txt"));
int c;
while ((c=myInput.read()) != -1)
myOutput.write(c);
myInput.close();
myOutput.close();
}catch(IOException e){}
}
}
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
49/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
50/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
51/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
52/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
53/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
54/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
55/58
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
56/58
The scanner classimport java.util.*;
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
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
57/58
p
/*Example using DataInputStream.*/
import java.io.DataInputStream;public class InputOutput{
public static void main(String[] as){
try{
DataInputStreamdis = 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
4Sum is 6
Binary vs TextFiles
8/13/2019 J2SE - Core Java - PG-DAC - Session- 7v2
58/58
Binary vs. TextFiles
pro con
BinaryEfficient in terms of
time and space
Pre information
about data neededto understand
content
Text Human readable,contains redundantinformation
Not efficient