R22 - JAVA UNIT - II (Files and I_O Streams).Pptx
R22 - JAVA UNIT - II (Files and I_O Streams).Pptx
JAVA
Files and I/O Streams
M. S . B. KASYAPA
Assistant Professor
Topics
UNIT - II
Syllabus
Exception Handling: Exception and Error, Exception Types,
Exception Handler, Exception Handling Clauses – try, catch,
finally, throws and the throw statement, Built-in-Exceptions
and Custom Exceptions.
Files and I/O Streams: The file class, Streams, The Byte
Streams, Filtered Byte Streams, The Random Access File
class.
M S B KASYAPA
Files and I/O Streams
★ Java I/O (Input and Output) is used to process the
input and produce the output.
★ Java uses the concept of a stream to make I/O
operations fast.
★ The File class in Java only represents the properties of
a file or directory.
★ Java provides a powerful I/O framework through its
java.io package. It includes classes for handling file
operations and streams.
★ However, it does not include classes to open network
sockets which are essential for network communication.
M S B KASYAPA
JAVA Files
★ The File class in Java only represents the properties of
a file or directory.
★ It doesn't handle the actual reading or writing of file
content. Instead, it provides methods for:
❖ Checking if a file exists.
❖ Creating new files or directories.
❖ Deleting files or directories.
❖ Renaming files.
❖ Getting file attributes (e.g., size, last modified date).
❖ Determining the file paths.
M S B KASYAPA
JAVA Files
★ File class is an abstract representation of files and
directory pathnames.
★ It acts as a descriptor, giving you information about a
file, not the file's contents.
★ It's often used in conjunction with stream classes to
perform actual I/O operations.
★ A pathname, whether abstract or in string form can be
either absolute or relative. The parent of an abstract
pathname may be obtained by invoking the getParent()
method of this class.
M S B KASYAPA
JAVA Files
★ First of all, we should create the File class object by
passing the filename or directory name to it.
★ A file system may implement restrictions to certain
operations on the actual file-system object, such as
reading, writing, and executing. These restrictions are
collectively known as access permissions.
★ Instances of the File class are immutable; that is, once
created, the abstract pathname represented by a File
object will never change.
M S B KASYAPA
Java Files
File Creation
A File object is created by passing in a string that represents the
name of a file, a String, or another File object. For example:
File object = new File("path_of_file / Filename");
File file1 = new File("myfile.txt");
Note: It only creates object no actual file
To create a actual File use createNewFile() method with file object.
file1.createNewFile();
Note: It gives true or false as output. true creates file if it not
exists and false means not possible to create file.
M S B KASYAPA
Java Files
File Class Constructors
Constructor Description
File(String pathname) Creates a File object representing the file or directory specified by
the pathname.
File(String parent, String child) Creates a File object from a parent directory and child pathname.
File(File parent, String child) Creates a File object from a File parent and a child pathname.
File(URI uri) Creates a File object from a URI (Uniform Resource Identifier).
M S B KASYAPA
Java Files
File Class Methods
File Information and Properties
Method Description
M S B KASYAPA
Java Files
File Class Methods
File Information and Properties
Method Description
M S B KASYAPA
Java Files
File Class Methods
File and Directory Manipulation
Method Description
M S B KASYAPA
Java Files
File Class Methods
File and Directory Manipulation
Method Description
M S B KASYAPA
Java Files
Create File Object with Constructors
M S B KASYAPA
Java Files
Create File Object with Constructors
M S B KASYAPA
Java Files
File Operations
M S B KASYAPA
Java Files
File Operations
M S B KASYAPA
JAVA Input, Output Streams
★ A stream is a sequence of data that flows from a source to a
destination.
★ It is also an abstraction representation of a sequence of data
elements, made available over time.
★ Streams can be generated or consumed one element at a time.
★ This makes them particularly useful when it's not feasible to
store the entire data set in memory at once.
★ In I/O, streams provide a way to read data from (input
streams) or write data to (output streams) various sources
and destinations, such as files, network connections, or
memory.
M S B KASYAPA
JAVA Input, Output Streams
★ Streams abstract the underlying I/O mechanisms, providing a
consistent interface for working with different data sources.
M S B KASYAPA
JAVA Input, Output Streams
M S B KASYAPA
JAVA Input, Output Streams
InputStream
OutputStream
M S B KASYAPA
JAVA Input, Output Streams
★ Streams can be broadly categorized into:
Byte Streams : (8-bit values).
❖ Deals with raw binary data.
❖ Ideal for handling file contents that are not text-based.
❖ Faster for non-text data.
Character Streams : (16-bit Unicode values).
❖ Deals with character data.
❖ Suitable for text-based files.
❖ Automatically handles character encoding (like UTF-8 or
UTF-16).
M S B KASYAPA
IO Streams
M S B KASYAPA
Java InputStream Class
InputStream Class
❖ It is the base of all the byte-based input streams classes.
❖ It represents an input stream of bytes. or sequence of data
flowing into a program from a source.
❖ This source can be a file on a hard drive, Data coming over a
network connection, Input from a keyboard, Data from
another program, An array of bytes in memory.
❖ As it is a abstract class to do operation it must be override.
❖ It has only one Constructor.
Constructor Description
M S B KASYAPA
Java InputStream Class
InputStream Class Methods
Method Description
void mark() marks the current position of the input stream. (saves position to
return later)
int read() reads next byte of data from the Input Stream. It returns the
byte as an integer (0 to 255)
int read(byte[] b, int off, int len) Reads len bytes from the stream into an array starting at off.
M S B KASYAPA
Java InputStream Class
InputStream Class Methods
Method Description
void close() closes the input stream and releases system resources associated with this
stream to Garbage collector.
long skip(long n) Skips over and discards n bytes of data from the input stream.
M S B KASYAPA
Java InputStream Class
InputStream SubClasses
❖ As it is a abstract class it can not create object to do
operations it must be inherited.
❖ All other InputStream classes in Byte Stream are subclasses
of InputStream.
Class Description
M S B KASYAPA
Java InputStream Class
InputStream SubClasses
Class Description
M S B KASYAPA
Java FileInputStream Class
FileInputStream Class
❖ FileInputStream class in Java is useful for reading data from
a file in the form of a Java sequence of bytes.
❖ FileInputStream is meant for reading streams of raw bytes
such as images, audio, and video.
❖ For reading streams of characters, consider using FileReader
(Part of Character Stream).
When to use:
❖ It mainly used for reading binary data from a file. and for
basic file reading where performance is not critical.
❖ When processing small files or files with raw byte data.
M S B KASYAPA
Java FileInputStream Class
FileInputStream
❖ As it is related Files and subclass of InputStream it supports
methods and constructs combined of two classes.
M S B KASYAPA
Java FileInputStream Class
FileInputStream Constructors
Constructor Description
FileInputStream(String name) Creates an input file stream to read from a file with the
specified name.
FileInputStream(File file) Creates an input file stream to read from the specified File
object.
FileInputStream(FileDescriptor fdobj) Creates an input file stream to read from the specified file
descriptor.
int available() Returns the number of bytes available to read in stream without blocking.
void close() Closes this file input stream and releases any system resources associated with
the stream.
void finalize() Ensures that the close method of this file input stream is called when there are no
more references to it.
getChannel() Returns the unique FileChannel object associated with this file input stream.
int read() Reads a single byte from the file and returns it as an int. Returns -1 if the end of
the file (EOF) is reached.
M S B KASYAPA
Java FileInputStream Class
FileInputStream Class Methods
Method Description
int read(byte[] b) Reads data into the specified byte array b. Returns the total number
of bytes read, or -1 if the end of the file is reached.
read(byte[] b, int off, int len) Reads up to len bytes of data from the file into the byte array b,
starting at index off. Returns the total number of bytes read.
long skip(long n) Skips over and discards n bytes of data from the input stream.
Returns the number of bytes actually skipped.
M S B KASYAPA
Java OutputStream Class
OutputStream Class
❖ OutputStream is an abstract class in the java.io package.
❖ It is the base of all the byte-based output streams classes.
❖ It represents an output stream of bytes. or sequence of data
flowing from a program to a files or memory.
❖ As it is a abstract class to do operation it must be override.
❖ It has only one Constructor.
Constructor Description
M S B KASYAPA
Java OutputStream Class
OutputStream Class Methods
Method Description
void write(byte[] b) Writes b.length bytes from the specified byte array to this
output stream. The b value is converted to a byte (b & 0xFF).
void write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset
off to this output stream.
void close() Closes this output stream and releases any system resources
associated with this stream.
void flush() Flushes this output stream and forces any buffered output
bytes to be written out.
M S B KASYAPA
Java OutputStream Class
OutputStream SubClasses
❖ As it is a abstract class it can not create object to do
operations it must be inherited.
❖ All other OutputStream classes in Byte Stream are subclasses
of OutputStream.
Class Description
M S B KASYAPA
Java OutputStream Class
OutputStream SubClasses
Class Description
M S B KASYAPA
Java FileOutputStream Class
FileOutputStream Class
❖ FileOutputStream class is a subclass of OutputStream. It is
used to write data to a file as a stream of bytes.
❖ It is is commonly employed for writing primitive values into a
file.
❖ It supports writing both byte-oriented and character-oriented
data. FileWriter is generally preferred for character-oriented
data.
❖ As it is related Files and subclass of FileOutputStream it
supports methods and constructs combined of two classes.
M S B KASYAPA
Java FileOutputStream Class
FileOutputStream Constructors
Constructor Description
FileOutputStream(File file, boolean append) Creates a file output stream object represented
FileOutputStream( String name, boolean append) by specified file object or name. Appends data
to the file if append is true
M S B KASYAPA
Java FileOutputStream Class
FileOutputStream Methods
Method Description
void finalize() It is used to clean up all the connection with the file output stream and finalize
the data.
getChannel() Returns the unique FileChannel object associated with this file output stream.
nullOutputStream() this method returns a new OutputStream which discards all bytes. The stream
returned is initially open.
M S B KASYAPA
Java FileOutputStream Class
FileOutputStream Class Methods
Method Description
void write(int b) It is used to write the specified byte to the file output stream.
void write(byte[] arr) It is used to write data in bytes of arr[] to file output stream.
void write(byte[] ary, int off, It is used to write the number of bytes equal to length to the output
int len) stream from an array starting from the position start.
flush() this method forces to write all data present in the output stream to
the destination(hard disk).
M S B KASYAPA
Java File Operations Program
Construct a Java Program to write content in a file and
copy the contents of that file into another file.
Process :
❖ Create a file and write content to it.
❖ Read the content from the file.
❖ Copy the content into another file.
Import Necessary Packages : Input and output stream,
exception and scanner for reading content from user.
M S B KASYAPA
Java File Operations Program
Construct a Java Program to write content in a file and
copy the contents of that file into another file.
Create file objects and call input and output process:
M S B KASYAPA
Java File Operations Program
Construct a Java Program to write content in a file and
copy the contents of that file into another file.
Writing a content into file:
❖ First create OutputStream as we need to write the data.
M S B KASYAPA
Java File Operations Program
Writing a content into file:
M S B KASYAPA
Java File Operations Program
Construct a Java Program to write content in a file and
copy the contents of that file into another file.
Copying one file data into another file:
❖ First create Input and Output Stream as we need to read data
from one file and write the data into another.
❖ Read the data from source file then write the content into
destination file until file end.
M S B KASYAPA
Java File Operations Program
Copying one file data into another file:
M S B KASYAPA
Java File Operations Program
Complete Program:
M S B KASYAPA
Filter Byte Streams
Filtered Byte Streams
❖ Filtered byte streams in Java provide a way to process
byte-oriented data with additional functionality.
❖ They are used to modify or enhance the functionality of input
and output streams by filtering the data that is read or
written.
❖ These are implemented using FilterInputStream and
FilterOutputStream classes, which are part of the java.io
package.
M S B KASYAPA
Filter Byte Streams
Filtered Byte Streams
❖ FilterInputStream and FilterOutputStream – These classes act
as wrappers around existing InputStream and OutputStream
objects.
❖ Filtered Byte Streams enhance the functionality of basic byte
streams by providing features like buffering, data type
handling, and object serialization.
❖ Byte Streams are ideal for low-level I/O operations, but for
better performance and advanced data processing, filtered
streams should be used.
M S B KASYAPA
Filter Byte Streams
Hierarchy of Filtered Streams
FilterInputStream FilterOutputStream
BufferedInputStream BufferedOutputStream
DataInputStream DataOutputStream
PushbackInputStream PrintStream
ObjectInputStream ObjectOutputStream
M S B KASYAPA
Filter Byte Streams
Hierarchy of Filtered Streams
java.lang.Object
└── java.io.InputStream
└── java.io.FilterInputStream
└── java.io.BufferedInputStream
java.lang.Object
└── java.io.OutputStream
└── java.io.FilterOutputStream
└── java.io.BufferedOutputStream
❖ These classes considered as both streams because These
inherits properties from InputStream/OutputStream and
FilterInputStream/FilterOutputStream to add buffering
functionality.
M S B KASYAPA
Filter Byte Streams
Byte Streams Filtered Byte Streams
Basic reading/writing of raw bytes Add additional functionality
Reads/Writes raw binary data Allows modification or enhancement
No default buffering Supports buffering and efficient data
transfer
Primitive Data Handling Does not Supports reading/writing of primitive
support primitives types using DataInputStream and
DataOutputStream
Object Serialization Not applicable Supports object serialization
Lower for large data processing Higher due to buffering and advanced
M S B KASYAPA
The Random Access File class
❖ The RandomAccessFile class in Java allows both reading and
writing to a file.
❖ It uses a large array of bytes and enabling direct access to any
position within the file using a file pointer.
❖ You to move the "file pointer" to a specific location and access
data directly, rather than sequentially.
❖ When creating a RandomAccessFile object, you specify the
access mode ("r" for read-only, "rw" for read/write).
❖ It is under java.io package
M S B KASYAPA
The Random Access File class
Constructor
Method
This creates a random access file stream to read from, and optionally to write to, the file specified by
the File argument.
This creates a random access file stream to read from, and optionally to write to, a file with the
specified name.
M S B KASYAPA
The Random Access File class
Methods
Method Description
void close() This method Closes this random access file stream and releases any
system resources associated with the stream.
getChannel() This method returns the unique FileChannel object associated with this file.
getFD() This method returns the file descriptor object associated with this stream.
long getFilePointer() This method returns the current offset in this file.
int skipBytes(int n) This method returns the unique FileChannel object associated with this file.
M S B KASYAPA
The Random Access File class
Methods
Methods for reading data from File
int read(), int read(byte[] b), int read(byte[] b, int off, int len), void readFully(byte[] b)
void writeBoolean(boolean v), void writeByte(int v), void writeBytes(String s), void
writeChar(int v), void writeChars(String s), void writeDouble(double v) ..etc
M S B KASYAPA
The Random Access File class
Program part1
M S B KASYAPA
The Random Access File class
Program part2
M S B KASYAPA
The Random Access File class
M S B KASYAPA
The Random Access File class
Output
M S B KASYAPA
Next Lecture on
JAVA
Packages
M. S . B. KASYAPA
Assistant Professor