0% found this document useful (0 votes)
15 views31 pages

Lecture 2.2.2

The document discusses Java's input and output stream classes, including byte and character streams, and the concepts of object serialization and deserialization. It covers various classes such as FileInputStream, FileOutputStream, and the use of the transient keyword in serialization. Additionally, it provides examples and references for further learning on Java I/O operations.

Uploaded by

madangleaming13
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)
15 views31 pages

Lecture 2.2.2

The document discusses Java's input and output stream classes, including byte and character streams, and the concepts of object serialization and deserialization. It covers various classes such as FileInputStream, FileOutputStream, and the use of the transient keyword in serialization. Additionally, it provides examples and references for further learning on Java I/O operations.

Uploaded by

madangleaming13
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/ 31

INSTITUTE : UIE

DEPARTMENT : CSE
Bachelor of Engineering (Computer Science &
Engineering)
PROJECT BASED LEARNING IN JAVA WITH LAB
(22CSH-359/22ITH-359)

TOPIC OF PRESENTATION:
Byte stream, Character stream, Object
serialization, cloning. (CO 4)
DISCOVER . LEARN .
EMPOWER
Lecture Objectives

In this lecture, we will


discuss:
•Byte stream,
Character stream,
Object serialization,
cloning.

2
Stream Classes
A stream is an abstraction that either produces or consumes information. A
stream is linked to a physical device by the Java I/O system.

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.

Java implements streams within class hierarchies defined in the java.io


package.
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.


The Byte Streams
InputStream is an abstract class that defines Java’s model of streaming byte input.
OutputStream is an abstract class that defines streaming byte output.
FileInputStream
The FileInputStream class creates an InputStream that you can use to read bytes from a file.

FileInputStream(String filepath)
FileInputStream(File fileObj) throw a FileNotFoundException

Eg::
FileInputStream f0 = new FileInputStream("/autoexec.bat")
File f = new File("/autoexec.bat");
FileInputStream f1 = new FileInputStream(f);

FileInputStream overrides six of the methods in the abstract class InputStream.

The mark( ) and reset( ) methods are not overridden, and any attempt to use reset( ) on a
FileInputStream will generate an IOException.
FileOutputStream
FileOutputStream creates an OutputStream that you can use to write bytes to a file.

FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)

filePath is the full path name of a file, and fileObj is a File object that describes the file.
If append is true, the file is opened in append mode.
ByteArrayInputStream
ByteArrayInputStream is an implementation of an input stream
that uses a byte array as the source.

ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)

ByteArrayOutputStream
ByteArrayOutputStream is an implementation of an output
stream that uses a byte array as the destination.

ByteArrayOutputStream( ) // a buffer of 32 bytes is


created
ByteArrayOutputStream(int numBytes)
Buffered Byte Streams
For the byte-oriented streams, a buffered stream extends a
filtered stream class by attaching a memory buffer to the I/O
streams.

This buffer allows Java to do I/O operations on more than a byte


at a time, hence increasing performance. Because the buffer is
available, skipping, marking, and resetting of the stream become
possible.

The buffered byte stream classes are BufferedInputStream and


BufferedOutputStream.
BufferedInputStream

Java’s BufferedInputStream class allows you to “wrap” any InputStream into a


buffered stream and achieve this performance improvement.

BufferedInputStream has two constructors:

BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize)
BufferedOutputStream

A BufferedOutputStream is similar to any OutputStream with the


exception of an added flush( ) method that is used to ensure that
data buffers are physically written to the actual output device.

BufferedOutputStream has two constructors:

BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int bufSize)
The Character Streams
Reader
Reader is an abstract class that defines Java’s model of streaming character input.
It implements the Closeable and Readable interfaces.
Writer

Writer is an abstract class that defines streaming character output.


It implements the Closeable, Flushable, and Appendable interfaces.
FileReader
The FileReader class creates a Reader that you can use to read the contents of a file.

FileReader(String filePath)
FileReader(File fileObj)
throw a FileNotFoundException.

FileWriter
FileWriter creates a Writer that you can use to write to a file.

FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)

throw an IOException.
CharArrayReader

CharArrayReader is an implementation of an input stream that


uses a character array as the source.

CharArrayReader(char array[ ])
CharArrayReader(char array[ ], int start, int numChars)

CharArrayWriter

CharArrayWriter is an implementation of an output stream that


uses an array as the destination.

CharArrayWriter( )
CharArrayWriter(int numChars)
Serialization
Object serialization is the process of saving an object's state to a sequence of bytes
(on disk), as well as the process of rebuilding those bytes into a live object at
some future time

• The Java Serialization API provides a standard mechanism to handle object


serialization

• You can only serialize the objects of a class that implements Serializable
interface.

After a serialized object is written to a file, it can be read from t he file and
deserialized (that is we can recreate the object in memory)

• The process of Serialization and DeSerialization is JVM independent. That is, an


object can be serialized on one platform and deserialized on an entirely different
platform.

• Classes ObjectInputStream and ObjectOutputStream are us ed for serialization &


deserialization.
Serializing Objects

• How to Write to an ObjectOutputStream


FileOutputStream out = new FileOutputStream("theTime");
ObjectOutputStream s = new ObjectOutputStream(out);
s.writeObject("Today");
s.writeObject(new Date());
s.flush();

• How to Read from an ObjectOutputStream


FileInputStream in = new FileInputStream("theTime");
ObjectInputStream s = new ObjectInputStream(in);
String today = (String)s.readObject();
Date date = (Date)s.readObject();
Object Serialization

package m10.io;

import java.io.*;
public 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;
}
}
Object Serialization

public class SerializationDemo {


public static void main(String args[]) {
try {
MyClass object1 = new MyClass(“Hello”, -7, 2.7e10);
System.out.println(“object1; “ + object1);
FileOutputStream fos = new FileOutputStream(“serial”);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
}
catch(Exception e) {
System.out.println(“Exception during serialization:“+ e);
System.exit(0);
}
Object Serialization

// Object Deserialization
try {
MyClass object2;
FileInputStream fis = new FileInputStream(“serial”);
ObjectInputStream ois = new ObjectInputSream(fis);
object2 = (MyClass)ois.readObject();
ois.close();
System.out.println(“object2: “ + object2);
}
catch(Exception e) {
System.out.println(“Exception during deserialization: “ + e);
System.exit(0);
}
}
}
The keyword : transient

transient keyword is used in Object Serialization.

By default, when you serialize an object, all its fields are serialized except for
static variables. When you construct this object back from its persistent state,
you will get the values of all the fields that are serialized(except static variables).

If you do not want to store the value of a particular non-static field, then you can
declare this field as transient.

This keyword is used only with a variable declaration.


The keyword : transient

Transient keyword provides us with the ability to control the ser ialization process
and gives us the flexibility to exclude some of object properties from serialization
process.

• Sometimes, it does make sense not to serialize certain attributes of an object. For
e.g. If you are developing an application for Weather forecasting and you have
created objects that store current weather conditions, the n storing current
temperature does not make much sense, since temperature keeps fluctuating and
you may not require the temp data at a later date when you de-serialize this object.
The keyword : transient

import java.io.*;
class Xyz implements Serializable {
double d1;
transient double d2;
static double d3;
void m1() {
System.out.println("The value of d1 is :" +d1);
System.out.println("The value of d2 is :" +d2);
System.out.println("The value of d3 is :" +d3);
}
}
The keyword : transient

class TransientExample1 {
public static void main(String [] args) throws IOException {
Xyz x = new Xyz();
x.d1=10.3;
x.d2=20.5;
x.d3=99.99;
x.m1();
FileOutputStream fx = new FileOutputStream("A1.xyz");
ObjectOutputStream ox = new ObjectOutputStream(fx);
ox.writeObject(x);
ox.flush();
}
}
The keyword : transient

import java.io.*;
class TransientExample2 {
public static void main(String [] args) {
try {
FileInputStream fx = new FileInputStream("A1.xyz");
ObjectInputStream ox = new ObjectInputStream(fx);
Xyz x = (Xyz) ox.readObject();
x.m1();
}
catch(Exception e) {
System.out.println(e);
}
}
}
Summary:

In this session, you were able to :

•Learn about IO Stream, Serialization and


deserialization.
References:
Books:
1. Balaguruswamy, Java.
2. A Primer, E.Balaguruswamy, Programming with Java, Tata McGraw
Hill Companies
3. John P. Flynt Thomson, Java Programming.

Reference Links:
https://www.javatpoint.com/java-io
https://www.tutorialspoint.com/java/java_files_io.htm
https://docs.oracle.com/javase/tutorial/essential/io/streams.html
https://www.programiz.com/java-programming/io-streams
http://tutorials.jenkov.com/java-io/streams.html

Video Links:
https://youtu.be/3YRahx2ltSg
https://youtu.be/mq-f7zPZ7b8
https://youtu.be/6B6vp0jZnb0
THANK YOU

You might also like