Mekdela Amba
University
Department of Software
engineering
Advanced programming(SEng6132)
Chapter 2 Java IO 1
Chapter - 2
Java Input/output
Chapter 2 Java IO 2
Outline
Streams
Various Stream classes
Using Streams
Object Streams
File Management
Chapter 2 Java IO 3
Introduction
Whenever programs produce output, the output may be
sent to either
The Java console, a text area, or some other GUI
component.
• These destinations are transitory, in the sense that the
output resides in the computer's primary memory and
exists only as long as the program is running.
Or to relatively permanent storage medium
A file is a collection of data stored on a disk or on
some other relatively permanent storage medium.
A file's existence does not depend on a running
program.
Chapter 2 Java IO 4
Java I/O
I/O = Input/output
In this context, it is input to and output from programs
• Input refers to information or data read from some
external source into a running program.
• Output refers to information or data written from a
running program to some external destination.
Input can be from keyboard, a file, or network connection
etc.
Output can be to display (screen) or a file
Advantages of file I/O:
• Permanent copy
• Output from one program can be input to another
• Input can be automated (rather than entered manually)
Chapter 2 Java IO 5
Cont…
The Java I/O package gives classes support for reading and
writing data to and from different input and output sources
including Arrays, files, strings, sockets, memory and other
data sources.
The [Link] package provides more than 60 input/output
classes (stream).
These classes are used to manipulate binary and text files.
Here, we will learn how to create files and how to perform
input and output operations on their data using the Java
classes designed specifically for this purpose.
Chapter 2 Java IO 6
STREAMS
Streams is the sequence of data. In java stream is
composed of bytes.
It is object that either delivers data to its destination
(screen, file, etc.) or that takes data from a source
(keyboard, file, etc.)
It acts as a buffer between the data source and destination
In java, three stream are created for us automatically:-
1. [Link]:- standard output stream
It connect a program to the screen.
2. [Link]:- standard input stream.
It connects a program to the keyboard.
3. [Link]:- standard error stream.
Chapter 2 Java IO 7
Streams
Java input and output is based on the use of streams.
Reading from a stream
A stream
Source reads
Program
Writing to a stream
writes A stream
Program
Destination
Chapter 2 Java IO 8
Types of Streams
There are two main type of stream. Those are
1. Byte stream
Java byte stream are used to perform input and output of 8-bit(1-
byte) at a time from binary file.
It can be classified into
i. InputSteam
ii. OutputStream
InputSteam and OutputStream class are most common used classes
of byte stream.
Chapter 2 Java IO 9
Chapter 2 Java IO 10
Byte InputSteam classes
11
Chapter 2 Java IO
Cont…
FileInputStream:- Input stream that read from file.
SquenceInputStream:- Used to combine two or
more input stream.
PipedInputStream:- Used to read from pipe.
ObjectInputStream:- Used to read an object from
InputStream.
ByteArrayInputStream:- Used to read a byte array
from InputStream.
StringBufferInputStream:- Used to read from a
StringBuffer object.
Chapter 2 Java IO 12
Cont…
FilterInputStream:- An instance of this class contain
some other input stream as a basic source of data for
further manipulation. It can be classified
BufferedInputStream:- provide buffer facility to the
input stream.
DataInputStream:- used to read primitive data type
from input stream.
PushBackInputStream:- Provide unreading facility to
the input stream.
Chapter 2 Java IO 13
Byte OutputStream classes
OutputStream:- will create a file, if doesn’t already exit, before opening
it for output.
Chapter 2 Java IO 14
Cont…
FileOutputStream:- used to write data into file.
PipedOutputStream:- used to write data into a pipe.
ObjectOutputStream:- used to write object to a
output stream.
ByteArrayOutputStream:- used to write data to a
byte array.
FilterOutputStream:-
BufferedOutputStream:- provide buffer facility to
output stream.
DataOutputStream:- used to write primitive data to a
output stream.
PrintStream:- used to print any data on output
stream. Chapter 2 Java IO 15
2. Character stream
It used to perform input and output of 16 bit/2 byte at a
time from character file.
It can be classified into
i. Reader
ii. Writer
Reader and Writer are most common used classes of
character stream.
Chapter 2 Java IO 16
Reader classes
Chapter 2 Java IO 17
Cont…
Reader class: with character-based streams, we can read lines of text.
Type and description of reader class
FileReader – used to read from files.
BuffereReader – sed to read text from a file line by line efficiently.
StringReader – used to read string.
And so on.
Chapter 2 Java IO 18
Writer classes
Chapter 2 Java IO 19
Cont…
Writer class :- abstract class that define character steam output. If
you need to change these values, you can use the
OutputStreamWriter. It include
FileWriter – used to write to files
BufferedWriter – provide buffer facility to the writer class.
FilterWriter – used to write filtered character streams.
PrintWriter – used to print any data to writer.
PipedWriter – used to write data to pipe.
Chapter 2 Java IO 20
Object Streams
In Java, Object Streams are used to read and write objects to a stream. These
streams are part of Java's serialization mechanism, which allows you to convert
an object into a byte stream and later reconstruct the object from that byte
stream.
• Key Concepts:
1. Serialization: The process of converting an object into a byte stream so that it
can be saved to a file, sent over a network, etc.
2. Deserialization: The reverse process of reading the byte stream and
reconstructing the original object.
Chapter 2 Java IO 21
Object Streams
For serializing the object, we call the writeObject() method
of ObjectOutputStream class, and
For deserialization we call the readObject() method
of ObjectInputStream class.
[Link] interface
Serializable is a marker interface (has no data member and method).
It is used to "mark" Java classes so that the objects of these classes
may get a certain capability.
The Serializable interface must be implemented by the class whose
object needs to be persisted.
Chapter 2 Java IO 22
Sample of code object serialization
public class JavaApplication3 {
package javaapplication3;
/** import [Link];
* @param args the command line arguments /**
*/ *
public static void main(String[] args) { * @author Administrator
// TODO code application logic here */
//Creating the object public class Stud implements Serializable{
Stud stu = new Stud(); public String name;
[Link]= "Abebe, "; public String address;
[Link] = " 01, Mekdela Amba"; }
try {
FileOutputStream fileout = new FileOutputStream("c:\\[Link]");
ObjectOutputStream out = new ObjectOutputStream(fileout);
[Link](stu);
[Link]();
[Link]();
[Link]("Success");
}
catch (IOException e){
[Link]();
}
}
Chapter 2 Java IO 23
Sample of code object deserialization
import [Link].*;
class Deserialization{ import [Link];
public static void main(String args[]){ public class Student implements Serializable{
try{ int id;
//Creating stream to read the object String name;
ObjectInputStream in=new ObjectInputStream(new Fil public Student(int id, String name) {
eInputStream("[Link]"));
[Link] = id;
Student s=(Student)[Link]();
[Link] = name;
//printing the data of the serialized object
}
[Link]([Link]+" "+[Link]);
}
//closing the stream
[Link]();
}
catch(Exception e){[Link](e);}
}
}
Chapter 2 Java IO 24
File management
The process and act of creating an
organized structure in which you store
information for easy retrieval.
It is all about file operation.
Naming a file
Opening a file -
Reading from a file
Writing data into a file
Closing a file
Chapter 2 Java IO 25
File opration
It include the following method and it function
createNewfile()- to create new file
Mkdir() – create directory
listFiles()- list all file and directory in the directory
Delete() – to delete file and directory
Length()- display the number of character in the file.
Sample of code for creating file
Import [Link].*;
Class Filecreate(){
Public static void main(string args[]){
File f = new File(“E:\\folder\\[Link]”);
[Link]();
}
}
Chapter 2 Java IO 26
Reading/Writing File
In java, there multiple ways to read data from a file and to write data to a
file.
Different ways:
1. Using Byte Stream (FileInputStream and FileOutputStream)
2. Using Character Stream (FileReader and FileWriter)
FileInputStream
allows reading data from a file.
While using FileInputStream, file must already exist it will generate error.
Implemented based on the byte stream.
provides a method read() to read data from a file byte by byte.
Syntax:
import [Link]
FileInputStream input = new FileInputStream(stringPath);
\\input stream that will be linked to the file specified by the path
FileInputStream input = new FileInputStream(File fileObject);
Chapter 2 Java IO 27
Cont…
It has the following Methods
read()
read(byte[] array)
read(byte[] array, int start, int length)
finalize()
Chapter 2 Java IO 28
Sample of code for FileInputStream
import [Link];
public class FileInputStreamDemo{
public static void main(String [] args){
try {
FileInputStream fi= new FileInputStream("[Link]");
// Assume the file has "The Storm is Coming!" [Link]([Link]());
int idx = [Link]();
while(idx != -1) {
[Link](idx);
// Result ?
idx = [Link]();
}
}
catch(Exception excpt){
[Link](excpt);
}
}
Chapter 2 Java IO 29
Cont…
FileOutputStream
It allows writing data to a file.
Iplemented based on the byte stream.
provides a method write() to write data to a file byte by byte.
There are two way to using file with FileOutputStream
1. FileOutputStream fout = new FileOutputStream(“c:/java/[Link]”);
Here is directly file path is specified while creating FileOutputStream.
2. File f = new File((“c:/java/[Link]”);
FileOutputStream fout = new FileOutputStream(f);
In the second method, first object of File is created and file object passed
to the FileOutputStream as a argument.
Chapter 2 Java IO 30
Cont…
Some of the method are
write(byte[] ary) - to write [Link] bytes from the
byte array to the file output stream
close() - used to closes the file output stream.
write(int b) - used to write the specified byte to the file
output stream
finalize() - clean up the connection with the file output
stream.
Chapter 2 Java IO 31
Sample of code for FileOutputStream
import [Link];
public class FileOutputStreamDemo {
public static void main(String[] args) {
String data = "The Storm is Coming!";
try { FileOutputStream output = new FileOutputStream("[Link]");
// byte[] array = [Link]();
// Writes byte to the file
[Link]([Link]());
// [Link](32);
[Link]();
[Link]();
}
catch (Exception e) {
[Link]();
}
}
}
Chapter 2 Java IO 32
Character Stream
FileReader
allows reading data from a file
implemented based on the character stream.
The FileReader class provides a method read() to read data from a file
character by character.
Syntaz:
import [Link]
FileReader read = new FileReader(“c:/java/[Link]”);
FileReader read = new FileReader(File fileObj);
It has the following method
read() –
read(byte[] array) –
read(byte[] array, int start, int length) –
getEncoding() –
Chapter 2 Java IO 33
Sample of code for FileReader
import [Link];
class FileReaderDemo {
public static void main(String[] args) {
// Creates an array of character
char[] array = new char[100];
try {
// Creates a reader using the FileReader
FileReader charReader = new FileReader("[Link]");
// Reads characters
[Link](array);
[Link](array);
// Closes the reader
[Link]();
}
catch(Exception e) {
[Link](e);
}
} Chapter 2 Java IO 34
Cont…
FileWriter
allows writing data from a file
implemented based on the character stream
The FileWriter class provides a method write() to write data from a file
character by character
Syntaz:-
import [Link]
FileWriter write = new FileWriter(String path);
FileWiter write = new FileWriter(File fileObj);
It has the following method
write()
write(char[] array)
write(String data)
getEncoding()
Chapter 2 Java IO 35
Sample of code for FileWriter
import [Link];
public class FileWriterDemo {
public static void main(String args[]) {
String data = "Just signaling a data to the output";
try {
// Creates a FileWriter
FileWriter output = new FileWriter("[Link]");
// Writes the string to the file
[Link](data);
// Closes the
writer [Link]();
}
catch (Exception e) {
[Link](e) ;
}
}
}
Chapter 2 Java IO 36
Reading Assignment
Chapter 2 Java IO 37
e r ?
a pt
ch
nd of
E
Chapter 2 Java IO 38