Chapter 4 - File IO
Chapter 4 - File IO
By: Sinodos G.
1
Introduction
2
Cont’d …
Byte oriented and numeric data is written with
output streams and read with input streams.
3
Cont’d …
The two main stream classes are
• java.io.InputStream
• java.io.OutputStream
4
Java Stream
a sequence of data [composed of bytes] of
undetermined length.
5
Cont’d …
Let's see the code to print output and error
message to the console.
System.out.println("simple message");
System.err.println("error message");
System.out.println((char)i);
• //it will print the character
6
Java Stream Classes
Most java stream classes are part of the java.io package
OutputStream:
Java application uses an output stream to write data
to a destination, it may be a file, an array, peripheral
device or socket.
InputStream:
Java application uses an input stream to read data
from a source, it may be a file, an array, peripheral
device or socket.
7
Cont’d …
8
Cont’d …
Some list of input and output java Streams :-
9
Output Stream
• It is the super class of all classes representing an
output stream of bytes.
• An output stream accepts output bytes and sends
them to some sink.
10
Input Stream class
11
File
A collection of information that is stored on a
computer and assigned a particular name.
12
Cont’d …
Files can be classified into two depending on the format
that is used.
Text files are often stored using the .txt extension, but
other file formats are also text formats, including .java
and .html files
13
Cont’d …
Binary files:
• are stored using an internal format that requires
special software to process.
14
Example:-
The following program calls a method that determines whether
a file exists, whether it can be read, what its length is and what
its absolute path is.
15
Useful class of FileObjects
16
Java FileOutputStream Class
Java FileOutputStream is an output stream used for
writing data to a file.
Used to :
write primitive values into a file
write byte-oriented as well as character-oriented data
For character-oriented data, it is preferred to use
FileWriter than FileOutStream.
Declaration
declaration into java.io.FileOutputStream class
public class FileOutputStream extends OutputStream
17
Methods:
finalize(): It is used to clean up the connection with
the file output stream.
18
Example:
19
Example 2
20
FileInputStream Class
FileInputStream class obtains input bytes from a file.
It is used for reading byte-oriented data (streams of
raw bytes) such as image data, audio, video etc.
21
FileInputStream class methods
available(): It is used to return the estimated number
of bytes that can be read from the input stream.
read(): It is used to read the byte of data from the
input stream.
read(byte[] b): It is used to read up to b.length bytes
of data from the input stream.
read(byte[] b, int len): It is used to read up to len
bytes of data from the input stream.
finalize(): It is used to ensure that the close method
is call when there is no more reference to the file
input stream.
close(): It is used to closes the stream.
22
Example: read single (first) character
23
Example 2
24
Java Buffered Stream
BufferedOutputStream Class
• Used for buffering an output stream.
• Internally uses buffer to store data.
• Adds more efficiency than to write data directly into
a stream. So, it makes the performance fast.
Syntax:
OutputStream os new BufferedOutputStream(new
FileOutputStream("D:\\IO Package\\test.txt"));
25
Constructors
BufferedOutputStream(OutputStream os)
Used for writing the data to the specified
output stream.
26
Methods
write (int b):
• It writes the specified byte to the buffered output
stream.
write(byte[] b, int off, int len):
• It write the bytes from the specified byte-input stream
into a specified byte array, starting with the given
offset
flush():
• It flushes the buffered output stream.
• Flushes the data of one stream and send it into
another. It is required if you have connected the one
stream with another.
27
Example
28
Cont’d …
BufferedInputStream Class
30
Sequence Streams
SequenceInputStream Class
• Used to read data from multiple streams.
31
Cont’d …
Constructors:
SequenceInputStream(InputStream s1, InputStream s2):
• creates a new input stream by reading
the data of two input stream in order,
first s1 and then s2.
SequenceInputStream(Enumeration e):
• creates a new input stream by reading
the data of an enumeration whose type
is InputStream.
32
Example1:
33
Example: writing the data of two files lab.txt and lab1.txt into
another file named student.txt
34
Cont’d …
35
36
Java Array Stream Class
Java ByteArrayOutputStream
Used to write common data into multiple files.
37
Cont’d …
Constructor:
ByteArrayOutputStream()
• Creates a new byte array output stream with the
initial capacity of 32 bytes, though its size increases if
necessary.
ByteArrayOutputStream(int size)
• Creates a new byte array output stream, with a
buffer capacity of the specified size, in bytes.
38
Example
39
Cont’d …
ByteArrayInputStream Class
It is a composed of two words: ByteArray and
InputStream.
40
Constructors
ByteArrayInputStream(byte[] ary)
• Creates a new byte array input stream which uses ary
as its buffer array.
41
Methods
int available():- It is used to return the number of
remaining bytes that can be read from the input
stream.
int read():- It is used to read the next byte of data
from the input stream.
int read(byte[] ary, int len): It is used to read up to
len bytes of data from an array of bytes in the input
stream.
reset(): It is used to reset the buffer of a byte array.
close(): It is used for closing a ByteArrayInputStream.
42
Example
43
Exercise
Write the following information at
D://Student//Ajava//Exercise using Any output Stream.
Information:
Java is a high level, robust and secured programming
language.
44
Java Data Streams
Java DataOutputStream Class
Allows an application to write primitive Java data
types to the output stream in a machine
independent way.
45
Example
46
Cont’d …
Java DataInputStream Class
47
Example:
48
Reading Assignment
50
Cont’d …
A file can be in any combination of following
permissible permissions:
51
Cont’d …
Java FilePermission Class
• Java FilePermission class contains the permission related
to a directory or file.
• All the permissions are related with path. The path can be
of two types.
• D:\\IO\\-: It indicates that the permission is associated with
all sub directories and files recursively.
• D:\\IO\\*: It indicates that the permission is associated with
all directory and files within this directory excluding sub
directories.
53
Cont’d …
Changing file permissions
A file can have any combinations of the following
permissions:
Executable
• setExecutable()
Readable
• setReadable()
Writable
• setWritable()
54
Cont’d ….
55
Java FileWriter Class
a subclass of Writer abstract class and it is used to write
a character, character array or a String to a file.
It is character-oriented class which is used for file
handling in java.
Unlike FileInputStream class, you don't need to convert
string into byte array because it provides method to
write string directly.
Declared in Java.io.FileWriter class:
56
Cont’d …
Constructor
FileWriter (String file):
• Creates a new file. It gets file name in string.
Methods
flush()
write(int c)
write(char[])
write(String str)
close()
57
Example: FileWriter class.
58
Java FileReader Class
59
Cont’d …
FileReader(String file)
• It gets filename in string. It opens the given file in read
mode. If file doesn't exist, it throws
• FileNotFoundException.
FileReader(File file)
• It gets filename in file instance. It opens the given file in
read mode. If file doesn't exist, it
• throws FileNotFoundException.
60
Cont’d …
Methods
• available()
gives the remaining number of bytes available to read
from this input stream.
• read()
reads one character at a time from this input character
stream.
• read(char[])
reads a whole character array at a time from this input
character stream.
• close()
closes this input stream and also frees any resources
connected with this input stream.
61
Example: reading the data from the text file test1.txt using
Java FileReader class.
62
Java PrintStream Class
provides methods to write data to another stream.
write data not only in terms of characters but also in
terms of primitive data types
like int, float, long, double and even an Object.
63
Cont’d …
Constructors
64
Example:
65
Directories in Java
A directory is a File which can contain a list of
other files and directories.
66
Creating Directories
There are two useful methods, which can be used to
create directories: -
67
Example
68
Listing Directories
List ( ) method: Provided by File object to list down
all the files and directories available in a directory.
69
Exercise
1. Write a program that creates the following
directories.
D://Student//Class//Java//Handout//Chapter1.doc
70
Solution Question Number 1:
71
Solution Question Number 2
72
Serialization
Java provides a mechanism, called object
serialization where an object can be represented as a
sequence of bytes that includes:-
The object's data as well as information about the
object's type and
In java serialization:
• The ObjectOutputStream: used for serializable (to write
objects) and
• The ObjectInputStream: used for deserializable (to read
object)
• The class must implement the java.io.Serializable
interface.
• When serializing an object to a file, the standard
convention in Java is to give the file a .ser extension.
74
Cont’d …
Advantage of Java Serialization
• Used to convert objects into stream.
75
java.io.Serializable Interface
76
Cont’d …
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
77
ObjectOutputStream class
Constructor
78
Important Methods
79
Example: Serialization
80
Deserialization
ObjectInputStream class
• An ObjectInputStream deserializes objects written using an
ObjectOutputStream.
Constructor
public ObjectInputStream(InputStream in)
• creates an ObjectInputStream that reads from the specified
InputStream
81
Methods
readObject() : reads an object from the input stream.
close(): closes ObjectInputStream.
82
The transient Keyword
Java transient keyword is used in serialization. If you
define any data member as transient, it
will not be serialized
83
Example:
84
Question
85