Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

File Handling in Java

This lecture discusses Java stream classes. It defines data streams and explains that streams are used for input/output operations in Java. It describes input, output, buffered input and output stream classes. It also covers character stream classes, serialization, and the need for serialization. Key classes discussed include File, FileInputStream, FileOutputStream, ObjectInputStream and ObjectOutputStream.

Uploaded by

HuZaM Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

File Handling in Java

This lecture discusses Java stream classes. It defines data streams and explains that streams are used for input/output operations in Java. It describes input, output, buffered input and output stream classes. It also covers character stream classes, serialization, and the need for serialization. Key classes discussed include File, FileInputStream, FileOutputStream, ObjectInputStream and ObjectOutputStream.

Uploaded by

HuZaM Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

LECTURE NO.

Presenter:
Muhammad Asim Ali Raza
Agenda
• Define data streams
• Explain the InputStream and OutputStream
classes
• Describe the BufferedInputStream and
BufferedOutputStream classes
• Describe Character stream classes
• Define Serialization and describe the need and
purpose of Serialization
Stream Classes

• A stream is a sequence of data or logical entity that


produces or consumes information.
• A data stream is a channel through which data travels
from a source to a destination.
• This source or destination can be an input or
output device, storage media or network
computers.
• A physical file can be read usingdifferent types of
streams, for example, FileInputStream or
FileReader.
• Java uses such streams to perform various input and
output operations.
Need for Stream Classes
• In Java, streams are required to perform all the input/output (I/O)
operations.
• Thus, Stream classes help in:

• Reading input from a stream.


1

• Writing output to a stream.


2

• Managing disk files.


3

• Share data with a network of computers.


4
Steps for Using Stream Classes
• To read or write data using Input/Output streams, the following steps
need to be performed. They are:
• Open a stream that points at a specific data source: a file, a socket, URL, and so on.
1

• Read or write data from/to this stream.


2

• Close the stream.


3

• Input and Output streams are abstract classes and are used
for reading and writing of unstructured sequence of bytes.
• For reading or writing bytes, a subclass of the InputStream
or OutputStream class has to be used respectively.
File Class
• File class directly works with files and the file system.
• A pathname can be absolute or relative.
• In an absolute pathname, no other information is required in order to
locate the required file as the pathname is complete.
• In a relative pathname, information is gathered from some other
pathname.
• A File object uses this path to locate a file.
• The constructors of the File class are as follows:
– File(String dirpath)
– File(String parent, String child)
– File(File fileobj, String filename)
– File(URL urlobj)
Methods of File Class

• The methods in File class help to manipulate the file on the file system.
• Some of the methods in the File class are:
– renameTo(File newname): Names the existing File object with the new name
specified by the variable newname.
– delete(): Deletes the file represented by the abstract path name.
– exists(): Tests the existence of file or directory denoted by this abstract pathname.
– getPath(): Converts the abstract pathname into a pathname string.
– isFile(): Checks whether the file denoted by this abstract pathname is a normal file.
– mkdir(): Creates the directory named by this abstract pathname.
– toPath(): Returns a java.nio.file.Path object constructed from the abstract
path.

. . .
File fileObj = new File(“C:/Java/Hello.txt”);
System.out.println(“Path is: “ +fileObj.getPath());
System.out.println(“Name is: “ +fileObj.getName());
System.out.println(“File exists is: “ +fileObj.exists());
System.out.println(“File is: “ +fileObj.isFile());
...
DataInput Interface and DataOutput Interface
• Data stream supports input/output of primitive data types and
string values. The data streams implement DataInput or
DataOutput interface.
• The DataInput interface has methods for:
– Reading bytes from a binary stream and convert the data to any of the Java
primitive types.
– Converting data from Java modified Unicode Transmission Format (UTF)-8
format into string form.
• The DataOutput interface has methods for:
– Converting data present in Java primitive type into a series of bytes and write
them onto a binary stream.
– Converting string data into Java-modified UTF-8 format and write it into a
stream.
java.io Package

• A stream represents many sources and destinations, such as


disk files and memory arrays.
• It is a sequence of data.
• An I/O Stream represents an input source or an output
destination.
• Streams support many forms of data, such as simple bytes,
primitive date type, localized characters and so on.
• Certain streams allow data to pass and certain streams
transform the data in an useful way.
• However, all streams provide a simple model to programs to
use them.
• A program uses an input stream to read data from a source. It
reads one item at a time.
java.io Package
The following figure illustrates the input stream model:

The following figure illustrates that a program uses an output stream to write
data to a destination:
java.io Package

The following Code Snippet displays the working of byte streams using the
FileInputStream class and FileOutputStream class:
Code Snippet

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamApp {
public static void main(String[] args) throws IOException {
FileInputStream inObj = null;
FileOutputStream outObj = null;
try {
inObj = new FileInputStream(“c:/java/hello.txt”);
outObj = new FileOutputStream(“outagain.txt”);
int ch;
while ((ch = inObj.read()) != -1) {
outObj.write(ch);
java.io Package [4-7]

}
} finally {
if (inObj != null) {
inObj.close();
}
if (outObj != null) {
outObj.close();
}
}
}
}

• In the Code Snippet, read() method:


– Reads a character and returns an int value which indicates that the end of the stream is
reached by returning a value of -1.
java.io Package

• A program that uses character streams adapts to the local character set and
is ready for internationalization.
• All character stream classes are derived from the Reader and Writer
class.
• There are character stream classes that specialize in file I/O operations such
as FileReader and FileWriter.
• The following Code Snippet displays the reading and writing of character
streams using the FileReader and FileWriter class:
Code Snippet
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CharStreamApp {
public static void main(String[] args) throws IOException {
FileReader inObjStream = null;
FileWriter outObjStream = null;
java.io Package
try {
inObjStream = new FileReader(“c:/java/hello.txt”);
outObjStream = new FileWriter(“charoutputagain.txt”);
int ch;
while ((ch = inObjStream.read()) != -1) {
outObjStream.write(ch);
}
} finally {
if (inObjStream != null) {
inObjStream.close();
}
}
}

• Character streams act as wrappers for byte streams.


• The character stream manages translation between characters and bytes
and uses the byte stream to perform the physical I/O operations.
java.io Package

• Character I/O typically occurs in bigger units than single


characters, such as a line that includes a string of characters
with a line terminator at the end.
• A line terminator can be any one of the following:
– Carriage-return/line-feed sequence (“\r\n”)
– A single carriage-return (“\r”)
– A single line-feed (“\n”).
• BufferedReader.readLine() and
PrintWriter.println() methods:
– The readLine() method returns a line of text with the line.
– The println() method outputs each line on a new line as it appends
the line terminator for the current operating system.
Chaining I/O Systems

• A program, typically, uses a series of streams to process the data.


• The following figure illustrates this:

• The following figure displays the chaining of an output stream:


Serialization and 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.
Serialization and Deserialization

• The byte stream created is platform independent. So,


the object serialized on one platform can be
deserialized on a different platform.
• To make a Java object serializable we implement
the java.io.Serializable interface.
The ObjectOutputStream class
contains writeObject() method for serializing an
Object.
public final void writeObject(Object obj)
throws IOException
Serialization and Deserialization

• The ObjectInputStream class


contains readObject() method for deserializing an
object.

• public final Object readObject() throws


IOException, ClassNotFoundException
Serialization

• Serialization is the process of reading and writing objects to a byte stream.


• An object that implements the Serializable interface will have its state
saved and restored using serialization and deserialization facilities.
• When a Java object’s class or superclass implements the
java.io.Serializable interface or its subinterface,
java.io.Externalizable, the Java object becomes serializable.
• The java.io.Serializable interface defines no methods.
• It indicates that the class should be considered for serialization.
• If a superclass is serializable, then its subclasses are also serializable.
• The only exception is if a variable is transient and static, its state cannot be
saved by serialization facilities.
• When the serialized form of an object is converted back into a copy of the
object, this process is called deserialization.
ObjectOutputStream Class

• ObjectOutputStream class extends the OutputStream class and


implements the ObjectOutput interface.
• It writes primitive data types and object to the output stream.
• The constructors of this class are as follows:
– ObjectOutputStream()
– ObjectOutputStream(OutputStreamout)
Methods in ObjectOutputStream Class:
writeFloat(float f)
writeObject(Object obj)
defaultWriteObject()
ObjectOutputStream Class

The following Code Snippet displays the use of methods of


ObjectOutputStream class:
Code Snippet

. . .
Point pointObj = new Point(50,75);
FileOutputStream fObj = new FileOutputStream(“point”);
ObjectOutputStream oos = new ObjectOutputStream(fObj);
oos.writeObject(pointObj);
oos.writeObject(new Date());
oos.close();
. . .
ObjectInputStream Class

The following Code Snippet displays the creation of an instance of


ObjectInputStream class:
Code Snippet

. . .
FileInputStream fObj = new FileInputStream(“point”);
ObjectInputStream ois = new ObjectInputStream(fObj);
Point obj = (Point) ois.readObject();
ois.close();

• In the Code Snippet, an instance of FileInputStream is created that


refers to the file named point.
• An ObjectInputStream is created from that file stream.
• The readObject() method returns an object which deserialize the
object.
• Finally, the object input stream is closed.
ObjectInputStream Class

• The ObjectInputStream class deserializes an object.


• The object to be deserialized must had already been created using the
ObjectOutputStream class.
• The following Code Snippet demonstrates the Serializable interface:
Code Snippet

import java.io.Serializable;
public class Employee implements Serializable{
String lastName;
String firstName;
double sal;
}
public class BranchEmpProcessor {
public static void main(String[] args) {
FileInputStream fIn = null;
FileOutputStream fOut = null;
ObjectInputStream oIn = null;
ObjectInputStream Class

ObjectOutputStream oOut = null;


try {
fOut = new FileOutputStream(“E:\\NewEmplyee.Ser”);
oOut = new ObjectOutputStream(fOut);
Employee e = new Employee();
e.lastName = “Smith”;
e.firstName = “John”;
e.sal = 5000.00;
oOut.writeObject(e);
oOut.close();
fOut.close();
fIn = new FileInputStream(“E:\\NewEmplyee.Ser”);
oIn = new ObjectInputStream(fIn);
//de-serializing employee
Employee emp = (Employee) oIn.readObject();
System.out.println(“Deserialized - “ +
emp.firstName + “ “ +
emp.lastName + “ from NewEmployee.ser”);
ObjectInputStream Class

} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
System.out.println(“finally”);
}
}
}
Summary

• A stream is a logical entity that produces or consumes information.


• Data stream supports input/output of primitive data types and String
values.
• InputStream is an abstract class that defines how data is received.
• The OutputStream class defines the way in which output is written to
streams.
• File class directly works with files on the file system.
• A buffer is a temporary storage area for data.
• Serialization is the process of reading and writing objects to a byte stream.
Questions?
Thank you !

You might also like