CS F213 Object Oriented Programming
IO streams, Files and Object serialization
Aritra Mukherjee, Dept. of CSIS
Java IO
Java brings various Streams with its I/O package that helps the user to perform all
the input-output operations. These streams support all the types of objects, data-
types, characters, files etc to fully execute the I/O operations.
Java IO
Three components:
System.in: This is the standard input
stream that is used to read characters
from the keyboard or any other
standard input device.
System.out: This is the standard
output stream that is used to produce
the result of a program on an output
device like the computer screen.
Java IO
Three components:
System.err: This is the standard error
stream that is used to output all the
error data that a program might throw,
on a computer screen or any standard
output device.
System.out and System.err uses
println() print() and
printf()
Types of Streams [input]
Types of Streams [Output]
Types of Streams [as per file types]
Types of Streams [Byte]
Stream class Description
BufferedInputStream It is used for Buffered Input Stream.
DataInputStream It contains method for reading java standard datatypes.
FileInputStream This is used to reads from a file
InputStream This is an abstract class that describes stream input.
Types of Streams [Byte]
Stream class Description
PrintStream This contains the most used print() and println() method
BufferedOutputStream This is used for Buffered Output Stream.
This contains method for writing java standard data
DataOutputStream
types.
FileOutputStream This is used to write to a file.
OutputStream This is an abstract class that describe stream output.
Byte Stream sample
Byte Stream sample
Byte Stream sample
Byte Stream sample
Types of Streams [Character]
Stream class Description
BufferedReader It is used to handle buffered input stream.
FileReader This is an input stream that reads from file.
InputStreamReader This input stream is used to translate byte to character.
OutputStreamReader This output stream is used to translate character to byte.
Types of Streams [Character]
Stream class Description
Reader This is an abstract class that define character stream input.
PrintWriter This contains the most used print() and println() method
Writer This is an abstract class that define character stream output.
BufferedWriter This is used to handle buffered output stream.
FileWriter This is used to output stream that writes to file.
Character file sample
Character file sample
Character file sample
Character file sample
Buffered Output Stream
Java.io.BufferedOutputStream class implements a buffered output stream. By
setting up such an output stream, an application can write bytes to the underlying
output stream without necessarily causing a call to the underlying system for each
byte written.
Fields
● protected byte[] buf: The internal buffer where data is stored.
● protected long count: The number of valid bytes in the buffer.
Buffered Output Stream
Java.io.BufferedOutputStream class implements a buffered output stream. By
setting up such an output stream, an application can write bytes to the underlying
output stream without necessarily causing a call to the underlying system for each
byte written.
Constructor and Description
● BufferedOutputStream(OutputStream out) : Creates a new buffered
output stream to write data to the specified underlying output stream.
● BufferedOutputStream(OutputStream out, int size) : Creates a
new buffered output stream to write data to the specified underlying output
stream with the specified buffer size.
Buffered Output Stream
Buffered Output Stream
Buffered Output Stream
Buffered Output Stream
File Object in Java
● Java File class is Java’s representation of a file or directory pathname.
● Because file and directory names have different formats on different
platforms, a simple string is not adequate to name them.
● Java File class contains several methods for working with the
pathname, deleting and renaming files, creating new directories, listing
the contents of a directory, and determining several common attributes
of files and directories.
Constructors
● File(File parent, String child): Creates a new File
instance from a parent abstract pathname and a child pathname string.
● File(String pathname): Creates a new File instance by
converting the given pathname string into an abstract pathname.
● File(String parent, String child): Creates a new File
instance from a parent pathname string and a child pathname string.
● File(URI uri): Creates a new File instance by converting the
given file: URI into an abstract pathname.
Examples
Examples
Examples
Examples
Methods of file class
Return
S. No. Method Description
Type
Tests whether the application can execute the file
1. canExecute() boolean
denoted by this abstract pathname.
Tests whether the application can read the file denoted
2. canRead() boolean
by this abstract pathname.
Tests whether the application can modify the file
3. canWrite() boolean
denoted by this abstract pathname.
4. compareTo(File pathname) Compares two abstract pathnames lexicographically. int
Methods of file class
Return
S. No. Method Description
Type
Atomically creates a new, empty file named by this
5. createNewFile() boolean
abstract pathname.
Deletes the file or directory denoted by this abstract
6. delete() boolean
pathname.
Tests whether the file or directory denoted by this
7. exists() boolean
abstract pathname exists.
Returns the absolute pathname string of this abstract
8. getAbsolutePath() String
pathname.
Methods of file class
Return
S. No. Method Description
Type
Returns an array of strings naming the files and
9. list() String[]
directories in the directory.
10. getFreeSpace() Returns the number of unallocated bytes in the partition. long
Returns the name of the file or directory denoted by this
11. getName() String
abstract pathname.
Returns the pathname string of this abstract pathname’s
12. getParent() String
parent.
Methods of file class
Return
S. No. Method Description
Type
Tests whether the file denoted by this pathname is a
13. isDirectory() boolean
directory.
Tests whether the file denoted by this abstract
14. isFile() boolean
pathname is a normal file.
Tests whether the file named by this abstract pathname
15. isHidden() boolean
is a hidden file.
Returns the length of the file denoted by this abstract
16. length() long
pathname.
Methods of file class
Return
S. No. Method Description
Type
Returns an array of abstract pathnames denoting the
22. listFiles() File[]
files in the directory.
23. mkdir() Creates the directory named by this abstract pathname. boolean
24. renameTo(File dest) Renames the file denoted by this abstract pathname. boolean
setExecutable(boolean A convenience method to set the owner’s execute
25. boolean
executable) permission.
Reading and writing object files
● Java object Serialization is an API provided by Java Library stack as a
means to serialize Java objects.
● Serialization is a process to convert objects into a writable byte stream.
Once converted into a byte-stream, these objects can be written to a
file. The reverse process of this is called de-serialization.
● A Java object is serializable if its class or any of its superclasses
implement either the java.io.Serializable interface or its
subinterface, java.io.Externalizable.
Reading and writing object files
● The objects can be converted into byte-stream using
java.io.ObjectOutputStream. In order to enable writing of objects
into a file using ObjectOutputStream, it is mandatory that the
concerned class implements Serializable interface.
● Reading objects in Java are similar to writing object using
ObjectInputStream.
● On reading objects, the ObjectInputStream directly tries to map all the
attributes into the class into which we try to cast the read object. If it is
unable to map the respective object exactly then it throws a
ClassNotFound exception.
What is serial version UID?
● If the serialVersionUID is missing, the JVM will create it automatically. The
serialVersionUID is something like version number; in short, if we save an
object with 1L, we need to provide the same 1L to read the object, else hits
an incompatible error.
● For example, we saved an object with serialVersionUID = 1L into a file
name person.obj. Later we add or delete some fields from the object, and
update serialVersionUID to 2L. Now, read the person.obj file and try to
convert it back to the modified object; since both serialVersionUID is
different, we will hit the invalidClassException
Why serialization is needed?
Some use cases for Java serialization:
● A data-interchange format between sockets, applications, clients, and
servers. It likes JSON or XML but in byte format.
● The serialization is the foundation of several critical Java’s technologies,
including Java Remote Method Invocation (Java RMI), Common Object
Request Broker Architecture (CORBA), and distributed computing such as
Java Naming and Directory Interface (JNDI), Java Management
Extensions (JMX) and Java Messaging (JMS).
Example
Example
Example
Example
Example
Example
Example
Java NIO basics
Java NIO(New Input/Output) is high-performance networking and file handling
API and structure which works as an alternative IO API for Java. It is
introduced from JDK 4. Java NIO works as the second I/O system after
standard Java IO with some added advanced features.
● Non-blocking IO operation: Java NIO performs non-blocking IO
operations. This means that it reads the data whichever is ready. For
instance, a thread can ask a channel to read the data from a buffer and the
thread can go for other work during that period and continue again from
the previous point where it has left. In the meantime, the reading operation
is complete which increases the overall efficiency.
Java NIO basics
Java NIO(New Input/Output) is high-performance networking and file handling
API and structure which works as an alternative IO API for Java. It is
introduced from JDK 4. Java NIO works as the second I/O system after
standard Java IO with some added advanced features.
● Buffer oriented approach: Java NIO’s buffer oriented approach allows us
to move forth and back in the buffer as we need. The data is read into a
buffer and cached there. Whenever the data is required, it is further
processed from the buffer.
Java NIO basics
Java NIO basics
Java NIO(New Input/Output) is high-performance networking and file handling
API and structure which works as an alternative IO API for Java. It is
introduced from JDK 4. Java NIO works as the second I/O system after
standard Java IO with some added advanced features.
● Selectors: Selectors are available for non-blocking I/O operations. A
selector is an object which monitors multiple channels for the events. As
Java NIO performs the non-blocking IO operations, selectors and the
selection keys with selectable channels defines the multiplexed IO
operations. So, in simple words, we can say that the selectors are used to
select the channels which are ready for the I/O operation.
Java NIO basics
Java NIO basics
The following are some of the things which were missing in the old package
and the reasons why the new package is used:
● The old module provides limited support for the symbolic links.
● The old module provides limited support for file attributes and performance
issues.
● The old module does not work consistently across all the platforms.
● The old module is missing with the basic operations like file copy, move,
etc.
And last but not least…