BASIC JAVA IO
Instructor:
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 1
Table of contents
◊ I/O Tutorial
◊ Binary Stream
◊ Character stream
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 2
Learning Approach
Noting down the key
concepts in the class
Completion of the project on
Analyze all the examples /
time inclusive of individual
code snippets provided
and group activities
Strongly suggested for
a better learning and
understanding of this
Study and understand all Study and understand the
course: self study topics
the artifacts
Completion of the self review Completion and submission of
questions in the lab guide all the assignments, on time
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 3
Section 1
I/O TUTORIAL
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 4
Overview
❖ 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 operation fast. The [Link]
package contains all the classes required for input and output operations.
❖ We can perform file handling in Java by Java I/O API.
❖ Stream:
A stream is a sequence of data. A stream is composed of bytes (It's called a stream
because it is like a stream of water that continues to flow).
Three streams are created for us automatically. All these streams are
attached with the console.
• 1) [Link]: standard output stream
• 2) [Link]: standard input stream
• 3) [Link]: standard error stream
[Link]("simple message");
[Link]("error message");
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 5
Java Stream
❖ A stream can be defined as a sequence of data. There are
two kinds of Streams −
InputStream − The InputStream is used to read data from a source.
OutputStream − The OutputStream is used for writing data to a
destination.
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 6
Binary streams
❖ Java byte streams are used to perform input and output of 8-bit bytes.
❖ Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
❖ Hierarchy class:
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 7
Character streams
❖ Java Byte streams are used to perform input and output of
8-bit bytes, whereas Java Character streams are used to
perform input and output for 16-bit unicode.
❖ Hierarchy class:
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 8
Section 2
BINARY STREAMS
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 9
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.
❖ Class Constructors:
No. Constructor & Description
1 FileInputStream(File file)
This creates a FileInputStream by opening a connection to an actual file, the file named by
the File object file in the file system.
2 FileInputStream(FileDescriptor fdObj)
This creates a FileInputStream by using the file descriptor fdObj, which represents an
existing connection to an actual file in the file system.
3 FileInputStream(String name)
This creates a FileInputStream by opening a connection to an actual file, the file named by
the path name name in the file system.
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 10
FileInputStream class
❖ Important methods:
No. Method & Description
1 void close()
This method closes this file input stream and releases any system resources associated with the
stream.
2 int read()
This method reads a byte of data from this input stream.
Returns: the next byte of data, or -1 if the end of the file is reached.
3 int read(byte[] b)
This method reads up to [Link] bytes of data from this input stream into an array of bytes.
Parameters: b - the buffer into which the data is read.
Returns: the total number of bytes read into the buffer, or -1.
4 int read(byte[] b, int off, int len)
This method reads up to len bytes of data from this input stream into an array of bytes.
Parameters: b - the buffer into which the data is read. off - the start offset in the destination array b
len - the maximum number of bytes read.
Returns: the total number of bytes read into the buffer, or -1
5 long skip(long x)
It is used to skip over and discards x bytes of data from the input stream.
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 11
FileInputStream class
❖ Important methods:
No. Method & Description
6 int available(): This method returns an estimate of the number of remaining bytes that can be read
(or skipped over) from this input stream without blocking by the next invocation of a method for this
input stream.
❖ Example:
public class ReadFile {
public static void main(String args[]) throws IOException {
// attach the file to FileInputStream
FileInputStream fin = new FileInputStream("[Link]");
// illustrating available method
[Link]("Number of remaining bytes:" + [Link]());
// illustrating skip method
/*Original File content:
* This is my first line
* This is my second line*/
[Link](5);
[Link]("FileContents :");
// read characters from FileInputStream and write them
int ch; Output:
while ((ch = [Link]()) != -1)
[Link]((char) ch); Number of remaining bytes:46
// close the file FileContents :
[Link](); is my first line
}
} This is my second line
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 12
FileOutputStream class
❖ FileOutputStream class belongs to byte stream and stores the data in
the form of individual bytes.
❖ Class constructor:
No. Constructor & Description
1 FileOutputStream(File file)
This creates a file output stream to write to the file represented by the specified File object.
2 FileOutputStream(File file, boolean append)
This creates a file output stream to write to the file represented by the specified File object.
3 FileOutputStream(FileDescriptor fdObj)
This creates an output file stream to write to the specified file descriptor, which represents an existing connection to an
actual file in the file system.
4 FileOutputStream(String name)
This creates an output file stream to write to the file with the specified name.
5 FileOutputStream(String name, boolean append)
This creates an output file stream to write to the file with the specified name.
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 13
FileOutputStream class
❖ Important methods:
void close() : Closes this file output stream and releases any system
resources associated with this stream.
protected void finalize() : Cleans up the connection to the file, and
ensures that the close method of this file output stream is called
when there are no more references to this stream.
void write(byte[] b) : Writes [Link] bytes from the specified byte
array to this file output stream.
void write(byte[] b, int off, int len) : Writes len bytes from the
specified byte array starting at offset off to this file output stream.
void write(int b) : Writes the specified byte to this file output stream.
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 14
FileOutputStream class
❖ Examples:
public class WriteFile {
public static void main(String[] args) throws IOException {
//attach keyboard to DataInputStream
DataInputStream dis=new DataInputStream([Link]);
// attach file to FileOutputStream
FileOutputStream fout=new FileOutputStream("[Link]");
//attach FileOutputStream to BufferedOutputStream
BufferedOutputStream bout=new BufferedOutputStream(fout,1024);
[Link]("Enter text (@ at the end):");
char ch;
//read characters from dis into ch. Then write them into bout.
//repeat this as long as the read character is not @
while((ch=(char)[Link]())!='@') {
[Link](ch);
}
//close the file
[Link]();
}
}
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 15
BufferedOutputStream Class
❖ BufferedOutputStream class is used for buffering an output stream.
It internally uses buffer to store data.
It adds more efficiency than to write data directly into a stream.
So, it makes the performance fast.
❖ Constructors:
Constructor Description
BufferedOutputStream(OutputStream os) It creates the new buffered output stream which
is used for writing the data to the specified output
stream.
BufferedOutputStream(OutputStream os, int size) It creates the new buffered output stream which
is used for writing the data to the specified output
stream with a specified buffer size.
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 16
BufferedOutputStream Class
❖ Methods:
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void 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
void flush() It flushes the buffered output stream.
❖ Example: } catch (FileNotFoundException e) {
[Link]("File testout not found!");
[Link]();
public class BufferedOutputStreamExample { } catch (IOException e) {
public static void main(String[] args) { [Link]("Cannot write to file!");
FileOutputStream fout = null; [Link]();
} finally {
BufferedOutputStream bout = null;
if (fout != null) {
try { try {
fout = new FileOutputStream("[Link]"); [Link]();
bout = new BufferedOutputStream(fout); } catch (IOException e) {
String s = "Welcome to FPT Software Academy."; [Link]();
}
byte b[] = [Link](); }
[Link](b); if (bout != null) {
[Link](); try {
[Link](); [Link]();
} catch (IOException e) {
[Link]();
[Link]();
[Link]("Success"); }
}
}
}
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use } 17
BufferedInputStream Class
❖ Java BufferedInputStream class is used to read information from stream.
It internally uses buffer mechanism to make the performance fast.
❖ The important points about BufferedInputStream are:
When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained
input stream, many bytes at a time.
When a BufferedInputStream is created, an internal buffer array is created.
❖ Constructor:
Constructor Description
BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it argument, the input
stream IS, for later use.
BufferedInputStream(InputStream IS, int size) It creates the BufferedInputStream with a specified buffer size and
saves it argument, the input stream IS, for later use.
❖ Main methods:
Method Description
int available() It returns an estimate number of bytes that can be read from the input stream without blocking by the
next invocation method for the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream into a specified byte array, starting with the given
offset.
void close() It closes the input stream and releases any of the system resources associated with the stream.
long skip(long x) It skips over and discards x bytes of data from the input stream.
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 18
try-with-resources statement
❖ In Java, the try-with-resources statement is a try statement that declares one or
more resources.
The resource is as an object that must be closed after finishing the program.
The try-with-resources statement ensures that each resource is closed at the end of the
statement execution.
❖ You can pass any object that implements [Link], which includes all
objects which implement [Link].
❖ The following example reads a string into a file. It uses an instance of
BufferedInputStream to read data into the file. BufferedInputStream is a resource that
must be closed after the program is finished with it. So, in this example, closing of resource
is done by itself try.
public class BufferedInputStreamExample {
public static void main(String[] args) {
try (FileInputStream fin = new FileInputStream("[Link]");
BufferedInputStream bfin = new BufferedInputStream(fin);) {
int data;
while ((data = [Link]()) != -1) {
[Link]((char) data);
}
} catch (FileNotFoundException exception) {
[Link]("File not found!");
} catch (IOException exception) {
[Link]("Cannot read from file!");
}
}
}
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 19
ObjectOutputStream class
❖ An ObjectOutputStream writes primitive data types and graphs of Java
objects to an OutputStream.
Only objects that support the [Link] interface can be written to streams.
The Java ObjectOutputStream is often used together with a Java
ObjectInputStream.
The ObjectOutputStream is used to write the Java objects, and the ObjectInputStream
is used to read the objects again.
❖ Class constructors :
protected ObjectOutputStream() : Provide a way for subclasses that are completely
reimplementing ObjectOutputStream to not have to allocate private data just used by
this implementation of ObjectOutputStream.
ObjectOutputStream(OutputStream out) : Creates an ObjectOutputStream that
writes to the specified OutputStream.
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 20
ObjectOutputStream class
❖ Important methods:
void writeObject(Object obj) : Write the specified object to the ObjectOutputStream.
❖ Examples:
public class ObjectOutputStreamDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileOutputStream fout = new FileOutputStream("[Link]");
ObjectOutputStream oot = new ObjectOutputStream(fout);
String a = "Fresher Academy";
String b = "Fresher";
byte[] be = { 'A', 'B', 'C' };
// illustrating writeInt(int i)
[Link](1);
// illustrating writeBoolean(boolean a)
[Link](true);
// illustrating writeObject(Object x)
[Link](a);
// illustrating writeBytes(String b)
[Link](b);
// illustrating writeDouble(double d)
[Link](2.3);
// illustrating writeUTF(String str)
[Link](a);
// illustrating writeChars(String a)
[Link](a);
// illustrating write(byte[] buff)
[Link](be);
// flushing the stream
[Link]();
[Link]();
}
}
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 21
ObjectInputStream class
The ObjectInputStream class deserializes primitive data and
public class ObjectInputStreamDemo {
objects previously written using an ObjectOutputStream. public static void main(String[] args)
Following are the important points about BufferedInputStream: throws IOException, ClassNotFoundException {
byte[] be = { 'A', 'B', 'C' };
❖ It is used to recover those objects previously serialized. It byte c[] = new byte[4];
ensures that the types of all objects in the graph created
from the stream match the classes present in the Java FileInputStream fin = new FileInputStream("[Link]");
Virtual Machine. ObjectInputStream oit = new ObjectInputStream(fin);
❖ Classes are loaded as required using the standard [Link]([Link]());
mechanisms. [Link]([Link]());
[Link]([Link]());
[Link](c);
for (int i = 0; i < 4; i++) {
[Link]((char) c[i]);
}
[Link]();
[Link]([Link]());
for (int i = 0; i < 13; i++) {
[Link]([Link]());
}
[Link]();
[Link]([Link]());
[Link](be);
for (int i = 0; i < 3; i++) {
[Link]((char) be[i]);
}
[Link]();
}
}
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 22
Example: write/read a user-defined class
❖ For serializing the object, we call the writeObject() method ObjectOutputStream, and for
deserialization we call the readObject() method of ObjectInputStream class.
❖ Create a class Student: We must have to implement the Serializable interface for
serializing the object.
public class Student implements Serializable {
private String ssn;
private String firstName;
private char mi;
private String lastName;
private LocalDate birthDate;
private String street;
private String phone;
private String zipCode;
public Student() {
}
public Student(String ssn, String firstName, char mi, String lastName,
LocalDate birthDate, String street, String phone, String zipCode) {
super();
[Link] = ssn;
[Link] = firstName;
[Link] = mi;
[Link] = lastName;
[Link] = birthDate;
[Link] = street;
[Link] = phone;
[Link] = zipCode;
}
//getter, setter methods
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 23
Example: write/read a user-defined class
❖ Create a class StudentService:
public class StudentService {
public boolean write(Student student)
throws FileNotFoundException, IOException {
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("[Link]"))) {
[Link](student);
}
return true;
}
public Student read() throws FileNotFoundException,
IOException, ClassNotFoundException {
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("[Link]"))) {
Student student = (Student) [Link](); // Upcasting
return student;
}
}
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 24
Example: write/read a user-defined class
❖ Create a main function in StudentService:
public static void main(String[] args) {
LocalDate birthDate = [Link](1999, 1, 1);
Student s1 = new Student("12345", "Nguyen Manh", 'K', "Truong", birthDate,
"Duytan", "0987654321", "084");
StudentService studentServices = new StudentService();
try {
[Link](s1);
[Link]("Complete write a student to file!");
[Link]("Reading file:");
[Link]([Link]());
} catch (IOException e) {
[Link]();
} catch (ClassNotFoundException e) {
[Link]();
}
}
}
Output:
Complete write a student to file!
Reading file:
Student [ssn=12345, firstName=Nguyen Manh, mi=K, lastName=Truong, birthDate=1999-01-01,
street=Duytan, phone=0987654321, zipCode=084]
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 25
Section 3
CHARACTER STREAM
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 26
BufferedWriter Class
❖ BufferedWriter class is used to provide buffering for Writer instances.
It makes the performance fast.
It inherits Writer class.
The buffering characters are used for providing the efficient writing of single arrays,
characters, and strings.
❖ Constructor and Methods:
Constructor Description
BufferedWriter(Writer wrt) It is used to create a buffered character output stream that uses the default size for
an output buffer.
BufferedWriter(Writer wrt, int size) It is used to create a buffered character output stream that uses the specified size for
an output buffer.
void newLine() It is used to add a new line by writing a line separator.
void write(int c) It is used to write a single character.
void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.
void write(String s, int off, int len) It is used to write a portion of a string.
void flush() It is used to flushes the input stream.
void close() It is used to closes the input stream
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 27
PrintWriter class
❖ Java PrintWriter class is the implementation of Writer class.
❖ It is used to print the formatted representation of objects to the text-output
stream.
❖ Class constructor:
PrintWriter(Writer out) → Can append
PrintWriter(Writer out, boolean autoFlush)
PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoFlush)
PrintWriter(String fileName) → Cannot append.
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 28
PrintWriter class
❖ To open a text file for output: connect a text file to a stream
for writing
PrintWriter outputStream = new PrintWriter(new FileOutputStream("[Link]"));
❖ Similar to the long way:
FileOutputStream s = new FileOutputStream("[Link]");
PrintWriter outputStream = new PrintWriter(s);
❖ Goal: create a PrintWriter object:
which uses FileOutputStream to open a text file.
❖ FileOutputStream “connects” PrintWriter to a text file.
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 29
Output File Streams
PrintWriter FileOutputStream
Memory Disk
smileyOutStream [Link]
PrintWriter smileyOutStream = new PrintWriter( new FileOutputStream(“[Link]”) );
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 30
Java Tip: Appending to a Text File
❖ To add/append to a file instead of replacing it, use a different
constructor for FileOutputStream:
outputStream = new PrintWriter(new FileOutputStream("[Link]", true));
[Link]("A for append or N for new file:");
char ans = [Link]().charAt(0);
boolean append = (ans == 'A' || ans == 'a');
outputStream = new PrintWriter(
new FileOutputStream("[Link]", append));
true if user enters 'A'
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 31
Closing a File
❖ An output file should be closed when you are done writing to it.
❖ An input file should be closed when you are done reading from it.
❖ Use the close method of the class PrintWriter,
BufferedReader.
[Link]();
❖ If a program ends normally it will close any files that are open.
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 32
BufferReader class
❖ To open a text file for input: connect a text file to a stream for
reading
Goal: a BufferedReader object,
• which uses FileReader to open a text file
FileReader “connects” BufferedReader to the text file
❖ For example:
BufferedReader smileyInStream = new BufferedReader
(new FileReader(“[Link]"));
❖ Similarly, the long way:
FileReader s = new FileReader(“[Link]");
BufferedReader smileyInStream=new BufferedReader(s);
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 33
Input File Streams
BufferedReader FileReader
Memory Disk
smileyInStream [Link]
BufferedReader smileyInStream = new BufferedReader( new FileReader(“[Link]”) );
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 34
Summary
◊ I/O Tutorial
◊ Binary Stream
◊ Character stream
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 35
Thank you
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy -
36
36
Internal Use