0% found this document useful (0 votes)
76 views66 pages

3rd Chap-Streams

plllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views66 pages

3rd Chap-Streams

plllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 66

The Stream classes – Byte streams and Character

streams, Reading console Input and Writing Console


Output, File class, Reading and writing Files, Random
access file operations, The Console class, Serialization,
Enumerations, auto boxing, generics.
Stream
• Java performs I/O through Streams.
• In general, a stream means continuous flow of data.
• A stream is linked to a physical device by the Java I/O system.

• A stream is an abstraction that either produces or consumes


information.
• An input stream can abstract many different kinds of input: from
a disk file, a keyboard, or a network socket.
• Likewise, an output stream may refer to the console, a disk file,
or a network connection.

• Streams are a clean way to deal with input/output without


having every part of your code understand the difference between
a keyboard and a network.
Stream
•. • Java’s stream-based I/O is built upon four
abstract classes: InputStream, OutputStream,
Reader, and Writer
• InputStream and OutputStream are designed
for byte streams. Reader and Writer are
• designed for character streams
Byte Streams and Character Streams
• Byte streams provide a convenient means for handling input
and output of bytes. They are used when reading or writing
binary data.
• A byte stream can be used with any type of object, including
binary data.
• Character streams provide a convenient means for handling
input and output of characters. They use Unicode and,
therefore, can be internationalized.
• The original version of Java (Java 1.0) did not include
character streams and, thus, all I/O was byte-oriented.
Character streams were added by Java 1.1
• at the lowest level, all I/O is still byte-oriented. The
character-based streams simply provide a convenient and
The Byte Stream Classes
• Byte streams are defined by using two class hierarchies. At
the top are two abstract classes: InputStream and
OutputStream
• Each of these abstract classes have several concrete
subclasses that handle the differences among various
devices, such as disk files, network connections, and even
memory buffers.
• To use the stream classes, java.io package must be
imported.
• The abstract classes InputStream and OutputStream define
several key methods that the other stream classes
implement. Two of the most important are read( ) and
write( ), which, respectively, read and write bytes of data
The Byte Stream Classes
The InputStream Class
• InputStream is an abstract class that defines Java’s
model of streaming byte input. Most of the
methods in this class will throw an IOException
when an I/O error occurs
• Table 20-1 shows the methods in InputStream.
The OutputStreamClass
• OutputStream is an abstract class that defines
streaming byte output.
• Most of the methods defined by this class return
void and throw an IOException in the case of I/O
errors.
• Table 20-2 shows the methods in OutputStream.
The Character Stream Classes
• Character streams are defined by using two class
hierarchies. At the top are two abstract classes:
Reader and Writer
• The abstract classes Reader and Writer define
several key methods that the other stream
classes implement. Two of the most important
methods are read( ) and write( ), which read
and write characters of data, respectively.
The Character Stream Classes
Predefined Streams
• System.out refers to the standard output
stream. By default, this is the console.
• System.in refers to standard input, which is
the keyboard by default.
• System.err refers to the standard error
stream, which also is the console by default.
However, these streams may be redirected to
any compatible I/O device.
Predefined Streams
• System.in is an object of type InputStream;
• System.out and System.err are objects of type
PrintStream. These are byte streams, even
though they are typically used to read and
write characters from and to the console.
• We can wrap these within character-based
streams, if desired.
Reading Console Input
• In Java 1.0, the only way to perform console
input was to use a byte stream.
• for commercial applications, the preferred
method of reading console input is to use a
character-oriented stream. This makes your
program easier to internationalize and
maintain.
Reading Console Input
• In Java, console input is accomplished by reading
from System.in. To obtain a character based
stream that is attached to the console, wrap
System.in in a BufferedReader object.
1. Because System.in refers to an object of type
InputStream, it can be used for inputStream
2. InputStreamReader converts bytes to characters.
To obtain an InputStreamReader object that is
linked to System.in, use the following constructor:
• InputStreamReader(InputStream ob)
3. To obtain a character based stream that is attached to
the console, wrap System.in in a Buffered reader
object.
4 BufferedReader supports a buffered input
streamReader obj
• A commonly used constructor is
BufferedReader(Reader inputReader)
5. Putting it all together, the following line of code creates
a BufferedReader that is connected to the keyboard:
• BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
6. After this statement executes, br is a character-based
stream that is linked to the console through System.in.
Reading Characters
import java.io.*;

class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader brob = new BufferedReader(new InputStreamReader
( System.in) );
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) brob.read();
System.out.println(c);
} while(c != 'q');
}
}
• int read( ) throws IOException
• Each time that read( ) is called, it reads a character from the input
stream and returns it as an integer value. It returns –1 when the end
of the stream is encountered.
Output:
Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q
System.in is line buffered, by default. This means that no input is
Reading Strings
• Readline(): To read a string from the keyboard, readLine( ) a member of the
BufferedReader class is used.
• String readLine( ) throws IOException
import java.io.*;
class BRReadLines {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader brob = new BufferedReader (new InputStreamReader (System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = brob.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
// A tiny editor.
import java.io.*;
class TinyEdit {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader brob = new BufferedReader(new
InputStreamReader(System.in));
String str[] = new String[100];
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
For (int i=0; i<100; i++)
{
str[i] = brob.readLine();
If (str[i].equals("stop")) break;
}
System.out.println("\nHere is your file:");
// display the lines
for(int i=0; i<100; i++) {
if(str[i].equals("stop")) break;
System.out.println(str[i]);
}
}
Writing Console Output
• Console output is most easily accomplished
with print( ) and println( ). These methods are
defined by the class PrintStream (which is the
type of object referenced by System.out).
• PrintStream also implements the low-level
method write( ). Thus, write( ) can be used to
write to the console.
• void write(int byteval)
• Although byteval is declared as an integer,
only the low-order eight bits are written.
• . // Demonstrate System.out.write().
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
• The PrintWriter class
• For real world programs, the recommended
method of writing to the console when using
Java is through a PrintWriter stream. PrintWriter
is one of the character-based classes.
• PrintWriter defines several constructors. One
among them is :
• PrintWriter(OutputStream outputStream,
boolean flushingOn)
• outputStream is an object of type OutputStream,
and flushingOn controls whether Java flushes the
output stream every time a println( ) method (among
others) is called.
• Writing Console Output
• PrintWriter supports the print( ) and println( )
methods. Thus, these methods can be used in the
same way as used them with System.out.
• If an argument is not a simple type, the PrintWriter
methods call the object’s toString( ) method and
then display the result.
The PrintWriter Class
// Demonstrate PrintWriter
import java.io.*;
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
The output from this program is shown here:
This is a string
-7
Reading and Writing Files
• Two of the most often-used stream classes are FileInputStream
and FileOutputStream, which create byte streams linked to
files.
• The following are the constructors that will be using to create
objects of files
1. FileInputStream(String fileName) throws
FileNotFoundException
2. FileOutputStream(String fileName) throws
FileNotFoundException.
• The file must be closed by calling the close( ) method, which is
implemented by both FileInputStream and FileOutputStream.
• void close( ) throws IOException
• Closing a file releases the system resources allocated to the file,
allowing them to be used by another file.
Reading Files
• To read from a file: use read() which is defined
within FileInputStream.
• int read( ) throws IOException
• Each time that it is called, it reads a single byte
from the file and returns the byte as an
integer value.
• read( ) returns –1 when the end of the file is
encountered.
• It can throw an IOException.
• Writing Console Output
// Use it as : java ShowFile TEST.TXT try
import java.io.*; {
class ShowFile { do {
public static void main(String args[]) i = fin.read();
{ if(i != -1)
int i; System.out.print((char) i);
FileInputStream fin; } while(i != -1);
if(args.length != 1) }
{ catch(IOException e)
System.out.println("Usage: { System.out.println("Error Reading
ShowFile filename“ ); File"); }
return; try {
} fin.close();
Try }
{ // Attempt to open the file. catch(IOException e)
fin = new FileInputStream(args[0]); { System.out.println("Error Closing
} File");}
catch(FileNotFoundException e) }
{ System.out.println("Cannot Open }
File");
return; }
• Writing Console Output
// Use it as : java ShowFile TEST.TXT try {
import java.io.*; fin = new FileInputStream(args[0]);
class ShowFile { do {
public static void main(String args[]) i = fin.read();
{ if(i != -1) System.out.print((char) i);
int i; } while(i != -1);
FileInputStream fin = null; } catch(FileNotFoundException e) {
System.out.println("File Not Found.");
if(args.length != 1) { } catch(IOException e) {
System.out.println("Usage: ShowFile System.out.println("An I/O Error
filename"); Occurred");
return; } finally {
} // Close file in all cases.
// The following code opens a file, reads try {
characters until EOF if(fin != null) fin.close();
// is encountered, and then closes the } catch(IOException e) {
file via a finally block. System.out.println("Error Closing File");
}}}}
Writing Files
• To write to a file, use the write( ) method
defined by FileOutputStream.
• void write(int byteval) throws IOException
• This method writes the byte specified by
byteval to the file. Although byteval is
declared as an integer, only the low-order
eight bits are written to the file.
• If an error occurs during writing, an
IOException is thrown.
• Writing Console Output
Writing file:
// java CopyFile FIRST.TXT SECOND.TXT do {
import java.io.*; i = fin.read();
class CopyFile { if(i != -1) fout.write(i);
public static void main(String args[]) throws } while(i != -1);
IOException }
{ catch(IOException e) {
int i; System.out.println("I/O Error: " + e);
FileInputStream fin = null; } finally {
FileOutputStream fout = null; try {
if(args.length != 2) { if(fin != null) fin.close();
System.out.println("Usage: CopyFile from }
to"); catch(IOException e2) {
return; System.out.println("Error Closing I/pFile");
} }
try { try {
// Attempt to open the files. if(fout != null) fout.close();
fin = new FileInputStream(args[0]); }
fout = new FileOutputStream(args[1]); catch(IOException e2) {
System.out.println("Error Closing Output
File");
}}}}
Random access file operations
• It is a special kind of file which allows non-sequential or random
access to any location in file.
• Random Access File class is used for reading and writing to
random access file.
• RandomAccessFile class is part of Java IO.
• While creating the instance the mode to open the file is to be
specified. To open the file for read only mode use “r” and for
read-write operations use “rw”.
• The read write operations can be done by moving the file pointer
to any location . If end-of-file is reached before the desired
number of byte has been read then EOFException is thrown.
• Using file pointer, data can be read or write at any position. To get
the current file pointer, use getFilePointer() method and to set the
file pointer index, use seek(int i) method.
Random Access File Constructors:
1. RandomAccessFile(File file, String mode)
2. RandomAccessFile(String name, String mode)
• Few Methods used :
• getFilePointer(),seek(long pos), write(int b),
read(), readInt(), writeDouble(double v),
length(),close()
• To get the current file pointer getFilePointer()
and to set the file pointer index seek(int) is
used.
Random Access File operations
Import java.io.IOException;
Import java.io.RandomAccessFile;
public class RAFdemo
static final String Filepath=“input.txt”;
Public static void main(string args[])
{
try{
System.out.println(new String (readfrom(Filepath,1,18)));
Writeto(“TKRCET”);
}
Catch(IOException e)
{
e.printStackTrace();
}
}
}
private static byte[] readfrom(string Filepath,int
pos, int size) throws IOException
{
RandomAccessFile raf= new
RandomAccessFile(Filepath,r);
raf.seek(pos);
byte b[]=new byte[size];
raf.read(b);
raf.close();
return (b);
}
private static b[] writeto(string Filepath,string
data,int pos) throws IOException
{
RandomAccessFile raf= new
RandomAccessFile(Filepath,rw);
raf.seek(pos);
raf.write(data.getbytes[]);
raf.close();
}
Console class
• The Java Console class is used to get input from console.
It provides methods to read texts and passwords.
• The java.io.Console class is attached with system console
internally. The Console class is introduced since 1.5.
• Console supplies no constructors. Instead, a Console
object is obtained by calling System.console( ), which is
shown here:
static Console console( )
• If a console is available, then a reference to it is
returned. Otherwise, null is returned.
• Console is primarily a convenience class because most of
its functionality is available through System.in and
System.out.
import java.io.*; // Java Program to demonstrate Console Methods
class ConsoleDemo
{
public static void main(String args[])
{
String str;
//Obtaining a reference to the console.
Console con = System.console();
/ Checking If there is no console available, then exit.
if(con == null)
{ System.out.print("No console available");
return;
}
// Read a string and then display it.
str = con.readLine("Enter your name: ");
con.printf(“ your name is: %s\n", str);
}
//to read password and then display it
System.out.println("Enter the password: ");
char[] ch=con.readPassword();
//converting char array into string
String pass = String.valueOf(ch);
System.out.println("Password is: " + pass);
}

sample output:
Enter your name: TKRCET
your name is: TKRCET
Enter the password:
Password is: TKR
Serialization
• Serialization is the process of writing the state of an
object to a byte stream.
• At a later time, these objects can be restored by using
the process of deserialization.
• Serialization is a mechanism of converting the state of
an object into a byte stream.
• Deserialization is the reverse process where the byte
stream is used to recreate the actual Java object in
memory. This mechanism is used to persist the object.
• The byte stream created is platform independent. So,
the object serialized on one platform can be
deserialized on a different platform.
• A class must implement Serializable interface present
in java.io package in order to serialize its object
successfully
• The ObjectOutputStream class
contains writeObject() method for serializing an Object.
public final void writeObject(Object obj) throws
IOException.
• The ObjectInputStream class
contains readObject() method for deserializing an
object.
public final Object readObject() throws IOException,
ClassNotFoundException
• Advantages of Serialization
1. This is useful when you want to save the
state of your program to a persistent storage
area, such as a file.
2. To travel an object across a network.
3. to implement Remote Method Invocation
(RMI). RMI allows a Java object on one machine
to invoke a method of a Java object on a
different machine.
import java.io.*;
class MyClass implements Serializable {
String s;
int i;
double d;
public MyClass(String s, int i, double d) {
this.s = s;
this.i = i;
this.d = d;
}
public String toString() {
return "s=" + s + "; i=" + i + "; d=" + d;
}}
public class SerializationDemo {
public static void main(String args[]) {
// Object serialization
Try{
ObjectOutputStream objOStrm =
new ObjectOutputStream(new FileOutputStream("serial"))
// FileOutputStream fos = new FileOutputStream(“serial”);
//ObjectOutputStream objOStrm = new ObjectOutputStream
(fos);
MyClass object1 = new MyClass("Hello", -7, 2.7e10);
System.out.println("object1: " + object1);
objOStrm.writeObject(object1);
}
catch(IOException e) {
System.out.println("Exception during serialization: " + e);
}
// Object deserialization
Try{
ObjectInputStream objIStrm =
new ObjectInputStream(new FileInputStream("serial"))

MyClass object2 = (MyClass)objIStrm.readObject();


System.out.println("object2: " + object2);
}
catch(Exception e) {
System.out.println("Exception during deserialization: " + e);
}}}
• This program demonstrates that the instance
variables of object1 and object2 are identical.
The output is shown here:
object1: s=Hello; i=-7; d=2.7E10
object2: s=Hello; i=-7; d=2.7E10
Enumerations
• An enumeration is a list of named constants.
• Beginning with JDK 5, enumerations were added
to the Java
• An enumeration is created using the enum
keyword.
• For example, here is a simple enumeration that
lists various apple varieties:
// An enumeration of apple varieties.
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
• The identifiers Jonathan, GoldenDel, and so on,
are called enumeration constants.
• Each is implicitly declared as a public, static
final member of Apple.
• Once an enumeration is defined, a variable of
that type can be created. Ex:
• Apple ap;
• Because ap is of type Apple, the only values
that it can be assigned (or can contain) are
those defined by the enumeration.
• For example, ap = Apple.RedDel;
assigns ap the value RedDel:
Enumeration values
• Can be compared using relational operators
• can also be used to control a switch statement.

The values( ) and valueOf( ) Methods


• All enumerations automatically contain two predefined methods:
values( ) and valueOf( ).
• Their general forms are shown here:
1. public static enum-type [ ] values( )
2. public static enum-type valueOf(String str )
• The values( ) method returns an array that contains a list of the
enumeration constants.
• The valueOf( ) method returns the enumeration constant whose
value corresponds to the string passed in str.
• In both cases, enum-type is the type of the enumeration.
// An enumeration of apple varieties.
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo {
public static void main(String args[])
{
Apple ap;
ap = Apple.RedDel;
// Output an enum value.
System.out.println("Value of ap: " + ap);
System.out.println();
ap = Apple.GoldenDel;
// Compare two enum values.
if(ap == Apple.GoldenDel)
System.out.println("ap contains GoldenDel.\n");
// Use an enum to control a switch statement.
switch(ap) {
case Jonathan:
System.out.println("Jonathan is red.");
break;
case GoldenDel:
System.out.println("Golden Delicious is yellow.");
break;
case RedDel:
System.out.println("Red Delicious is red.");
break;
case Winesap:
System.out.println("Winesap is red.");
break;
case Cortland:
System.out.println("Cortland is red.");
break;
}
}
}
The output from the program is shown here:
Value of ap: RedDel
ap contains GoldenDel.
Golden Delicious is yellow.
Type Wrappers
• Java uses primitive types (also called simple types), such
as int or double, to hold the basic data types supported
by the language.
• Despite the performance benefit offered by the primitive
types, there are times when you will need an object
representation.
• For example, i) a primitive type can not be passed by
reference to a method. Ii) any of the standard data
structures implemented by Java operate on objects, which
means that these data structures can’t be used to store
primitive types.
• To handle these (and other) situations, Java provides
type wrappers, which are classes that encapsulate a
primitive type within an object.
• Character
• Character is a wrapper around a char. The
constructor for Character is
Character(char ch)
Here, ch specifies the character that will be
wrapped by the Character object being created.
• To obtain the char value contained in a
Character object, call charValue( ), shown here:
• char charValue( )
• It returns the encapsulated character.
• The Numeric Type Wrappers
• The most commonly used type wrappers are those that
represent numeric values.
• These are Byte, Short, Integer, Long, Float, and Double. All of
the numeric type wrappers inherit the abstract class Number.
• Number declares methods that return the value of an object in
each of the different number formats. These methods are
shown here:
byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )
• For example, doubleValue( ) returns the value of an object as a
double
• // Demonstrate a type wrapper.
class Wrap {
public static void main(String args[]) {
Integer iOb = new Integer(100);
int i = iOb.intValue();
System.out.println(i + " " + iOb); // displays 100 100
}
}
• This program wraps the integer value 100 inside
an Integer object called iOb.
• The program then obtains this value by calling
intValue( ) and stores the result in i.
• Autoboxing and unboxing
• The process of encapsulating a value within an
object is called boxing.
• Thus, in the above program, this line (Integer
iOb = new Integer(100);) boxes the value 100
into an Integer:
• The process of extracting a value from a type
wrapper is called unboxing.
• For example, the program unboxes the value
in iOb with this statement:
• int i = iOb.intValue();
• Autoboxing and unboxing
• Autoboxing is the process by which a primitive
type is automatically encapsulated (boxed) into
its equivalent type wrapper whenever an object
of that type is needed.
• There is no need to explicitly construct an
object.
• Auto-unboxing is the process by which the
value of a boxed object is automatically
extracted (unboxed) from a type wrapper when
its value is needed.
• There is no need to call a method such as
intValue( ) or doubleValue( ).
// Demonstrate autoboxing/unboxing.
class AutoBox {
public static void main(String args[]) {
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
System.out.println(i + " " + iOb);
// displays 100 100
}
}
• Autoboxing and unboxing:
1. autoboxing/unboxing might occur when an
argument is passed to a method, or when a
value is returned by a method.
2. Within an expression, a numeric object is
automatically unboxed. The outcome of the
expression is reboxed, if necessary.
Generics
• generics means parameterized types.
• Introduced by JDK 5,
• generics are similar to templates in C++ but not same.
• generics allow type (Integer, String, … etc and user defined
types) to be a parameter to methods, classes and interfaces
• Generic types are instantiated to form parameterized types
by providing actual type arguments that replace the formal
type parameters.
• we use <> to specify parameter types in generic class
creation.
• Ex: A class like LinkedList<E> is a generic type, that has a
type parameter E .
Instantiations, such as LinkedList<Integer> or
a LinkedList<String>, are called parameterized types, and
// A simple generic class. Here, T is a type parameter that will be
replaced by a real type when an object of type Gen is created.
class Gen<T>
{
T ob; // declare an object of type T

Gen(T o) {
ob = o;
}
// Return ob.
T getob() {
return ob;
}
// Show type of T
void showType() {
System.out.println("Type of T is " + ob.getClass().getName());
}
}
• GenDemo {
class
public static void main(String args[]) {
Gen<Integer> iOb;
iOb = new Gen<Integer>(88);
iOb.showType();
int v = iOb.getob();
System.out.println("value: " + v);
System.out.println();
Gen<String> strOb = new Gen<String> ("Generics Test");
strOb.showType();
String str = strOb.getob();
System.out.println("value: " + str);} }
Output:
Type of T is java.lang.Integer
value: 88
Type of T is java.lang.String
value: Generics Test
Advantages:
1. A method/class/interface can be written
once and use for any type we want.
2. Generics make errors to appear compile
time than at run time
3. By using generics, we can implement
algorithms that work on different types of
objects and at the same they are type safe
too.

You might also like