Advanced Programming (ITec3054)
Input / Output
Thursday, August 15, 2024 By Melese E., Department of Computer Science 1
Java I/O
• Java I/O uses a concept called stream.
• Stream
• is an abstraction that either produces or consumes information
• is linked to a physical device by the Java I/O system
• Console, file, network, etc.
• All streams behave in the same manner, even if the actual physical devices to which
they are linked differ
• As a result, the same I/O classes and methods can be applied to different types of
devices
• This means that an input stream can abstract many different kinds of input: a disk file, a
keyboard, or a network socket
• The same is true for an output stream
• The hierarchy of stream classes are defined in the [Link] package
Thursday, August 15, 2024 By Melese E., Department of Computer Science 2
Java I/O
• Java defines two types of I/O streams: Byte stream and character stream
• Byte Stream
• provide a convenient means for handling input and output of bytes
• In other words, the byte stream is used for reading or writing binary data
• Character Stream
• provide a convenient means for handling input and output of characters
• Use Unicode => internationalization is possible
• In the background, at the lowest level, I/O is byte oriented
• In most cases, the character stream is preferred, except for cases that force
us to manipulate bits directly, such as implementing an
encryption/decryption algorithm
Thursday, August 15, 2024 By Melese E., Department of Computer Science 3
Java I/O – The Byte Stream Classes
• are defined by using two class hierarchies
• The class hierarchy for input – the super class is an abstract class called InputStream
• The class hierarchy for output – the super class is an abstract class called
OutputStream
• The InputStream and OutputStream classes define key methods that the
subclasses implement (must implement);
• The two most important are the read() (by InputStream) and write() (by OutputStream)
methods
• Each of these abstract classes has several concrete subclasses
• These concrete classes handle the differences among various devices, such as
• disk files,
• network connections,
• and even memory buffers
Thursday, August 15, 2024 By Melese E., Department of Computer Science 4
Java I/O – The Byte Stream Classes
• Some of the byte stream classes in the [Link] package are
• BufferedInptuStream – for reading from a buffer
• BufferedOutputStream – for writing to a buffer
• ByteArrayInptuStream – for reading from a byte array
• ByteArrayOutputStream – for writing into a byte array
• DataInptuStream – for reading java standard data types (int, long, ..)
• DataOutputStream – for writing java standard data types
• FileInptuStream – for reading from a file
• FileOutputStream – for writing to a file
• InputStream – the super class of all classes that are used for input
• ObjectInptuStream – for serializing object (reading object)
• ObjectOutputStream – for writing object
• OutputStream – the super class of all classes that are used for output
• PrintStream – an output stream class that contains the print() and println() methods
• This means the out object in the System class is a type of PrintStream
Thursday, August 15, 2024 By Melese E., Department of Computer Science 5
Java I/O – The Character Stream Classes
• These are also defined using two hierarchies
• The class hierarchy for input – the super class is an abstract class called Reader
• The class hierarchy for output – the super class is an abstract class called Writer
• These classes handle Unicode character streams
• The Reader and Writer classes define key methods that the subclasses implement
(must implement);
• The two most important are the read() (by Reader) and write() (by Writer) methods
• Each of these abstract classes has several concrete subclasses
• These concrete classes handle the differences among various devices, such as
• disk files,
• network connections,
• and even memory buffers
Thursday, August 15, 2024 By Melese E., Department of Computer Science 6
Java I/O – The Character Stream Classes
• Some of the character stream classes in the [Link] package are
• BufferedReader – reading character from a buffer
• BufferedWriter – writing character into a buffer
• CharArrayReader – reading from a character array
• CharArrayWriter – writing to a character array
• FileReader – reading character from a file
• FileWriter – writing character to a file
• InputStreamReader – Input stream that translates bytes to characters
• LineNumberReader – Input stream that counts lines
• OutputStreamWriter – Output stream that translates characters to bytes
• PrintWriter - Output stream that contains print( ) and println( )
• Reader – the super class of all character input classes
• StringReader – Input stream that reads from a string
• StringWriter – Output stream that writes to a string
• Writer – the super class of all character output classes
Thursday, August 15, 2024 By Melese E., Department of Computer Science 7
Java I/O – The System class
• Contains, among others, three I/O related objects defined as public, static
and final. These are
• [Link] – which is a type of PrintStream class and by default it is the console
• [Link] – which is a type of InputStream class and by default it is the keyboard
• [Link] – which is a type of PrintStream class and by default it is the console
• All the three are byte stream types
• But you can wrap these within character-based streams, if desired
Thursday, August 15, 2024 By Melese E., Department of Computer Science 8
Java I/O – Reading from console
• Console input is accomplished (either directly or indirectly) by reading from [Link]
• One of the ways is to wrap [Link] in a BufferedReader – its common constructor is
• BufferedReader(Reader inputReader)
• inputReader argument is an object of type of Reader that wraps the [Link]
• Since [Link] is byte stream, we need a subclass of Reader that converts byte stream into character stream – the
InputStreamReader class is the right one
• Its common constructor is
• InputStreamReader(InputStream inputStream) – the [Link] is passed as the inputStream object
• Before JDK 17, the following statement is enough to create a buffered reader object attached to
the keyboard
• BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
• JDK 17 and higher – the character set for the keyboard needs to be included
• Console c = [Link]();
• If(c == null) return;
• BufferedReader br = new BufferedReader(new InputStreamReader([Link], [Link]()));
• If you are sure the console is present, use the following
• BufferedReader br = new BufferedReader(new InputStreamReader([Link], [Link]().charset()));
Thursday, August 15, 2024 By Melese E., Department of Computer Science 9
Java I/O – Reading from console
• After creating the BufferedReader object, you can use
• The read() method – which reads a character and return it as an integer value (you need type
conversion)
• The readLine() method – which reads a line and returns it as a string
• Both methods throw IOException – if an attempt is made to read at the end of
the input stream
• Either you need to put the methods in a try … catch or make the enclosing method to throw
IOException
• An input is read from the keyboard whenever you press the enter key
• The read() method reads the input character by character when you press the enter key =>
you need to use a loop to read each character
• The readLine() method reads what you have wrote as a single string object when you press
the enter key – a line in this case is any input between the previous pressing of enter key and
the current pressing of the enter key
Thursday, August 15, 2024 By Melese E., Department of Computer Science 10
Java I/O – Reading from console
//a program that reads each character until it finds the letter ‘q’
import [Link].*;
public class ConsoleInput {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader([Link], [Link]().charset()));
char c;
do{
c = (char)[Link]();
if(c!='\n' && c!='\r')
[Link](c + " - input");
}while(c!='q');
}
}
Thursday, August 15, 2024 By Melese E., Department of Computer Science 11
Java I/O – Reading from console
//repeatedly read a line of string until you find the word 'quit'
import [Link].*;
public class ReadLine {
public static void main(String[] args){
BufferedReader br = new BufferedReader(new InputStreamReader([Link], [Link]().charset()));
String st="";
do {
try{
st = [Link]();
}catch(IOException ex){
[Link]("An IO error has occurred");
}
[Link]("Input: " + st);
}while();
}
}
Thursday, August 15, 2024 By Melese E., Department of Computer Science 12
Java I/O – Reading from console
• You can also use other character streams or byte streams to perform
console I/O – the concept is same
• attach the [Link] to the object you are creating and
• use the methods available in the specific object you created
Thursday, August 15, 2024 By Melese E., Department of Computer Science 13
Java I/O – The Concept of Streams
• Using same classes to perform I/O on different devices
• Using BufferedReader, for example, for file input in the same way we used it for
console input
• The difference is we attach [Link] to the BufferedReader in the case of console input; the
FileReader instance is attached to the BufferedReader in the case of file input
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
int i=0;
while(i!=-1){
i= [Link]();
if(i!=-1)
[Link]((char)i);
}
Thursday, August 15, 2024 By Melese E., Department of Computer Science 14
Java I/O – File I/O
• To perform file input / output
• You can either use character oriented or byte oriented streams
• Using the byte oriented streams
• First create an object of FileInputStream for input – or an object of FileOutputStream
for output
• Then you either use these objects directly or attach them to other byte oriented
stream objects
• such as BufferedInputSteam, DataInputStream, ObjectInputSteam, etc for FileInputStream
• Use the corresponding classes for the FileOutputStream too
• Using the character oriented streasms
• First create an object of FileReader for input – or an object of FireWriter for output
• Then you either use these objects directly or attach them to other character oriented
stream objects
Thursday, August 15, 2024 By Melese E., Department of Computer Science 15
Java I/O – File I/O – Byte Oriented Streams
• The following are some of the common methods specified by the InputStream class and inherited
by all other byte oriented classes
• void close() – closes an opened stream
• int read() – reads a byte from the stream and returns it as an int
• int read(byte[] buffer) – reads an array of bytes and stores it into buffer and returns the number of bytes read
• byte[] readAllBytes() – beginning at the current position, reads to the end of the stream, returning a byte
array that holds the input
• byte[] readNBytes(int numBytes) – attempts to read numBytes bytes, returning the result in a byte array. If
the end of the stream is reached before numBytes bytes have been read, then the returned array will contain
less than numBytes bytes
• The following are some of the common methods specified by OutputStream class
• void close() – closes the output stream. Further write attempts will generate an IOException
• void flush() – finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers
• void write(int b) – writes a single byte to an output stream. Note that the parameter is an int, which allows
you to call write( ) with an expression without having to cast it back to byte
• void write(byte[] buffer) – writes a complete array of bytes to an output stream
• The above methods are either inherited or overridden by subclasses
• In addition to these methods, subclasses may specify their own methods
Thursday, August 15, 2024 By Melese E., Department of Computer Science 16
Java I/O – File I/O – Byte Oriented Streams
• In this course, we will use File I/O to demonstrate I/O streams of Java
• In the same way as will be demonstrated, the stream classes can be used with other I/O
devices such as the console, the network, etc …
• To write data into a file
• First create an object of FileOutputStream as follows
• FileOutputStream fos = new FileOutputStream(“filename”);
• Then use the above methods to write data into the file as follows
import [Link].*;
class FileOSDemo{
public static void main(String[] args) throws IOException{
FileOutputStream fos = new FileOutputStream("[Link]");
[Link]((int)'a');
String data = "This is a string data";
byte[] byteData = [Link]();
[Link](byteData);
[Link]();
}
}
Thursday, August 15, 2024 By Melese E., Department of Computer Science 17
Java I/O – File I/O – Byte Oriented Streams
• To read from a file
• First create an object of the FileInputStream class
• FileInputStream fis = new FileInputStrea(“filename”);
• Then use the above methods to read in the way you like
import [Link].*;
class FileISDemo{
public static void main(String[] args) throws IOException{
FileInputStream fis = new FileInputStream("[Link]");
char c = (char)[Link]();
[Link](c);
byte[] buffer = new byte[5];
[Link](buffer);
[Link](new String(buffer));
byte[] buffer2;
buffer2 = [Link]();
[Link](new String(buffer2));
[Link]();
}
}
Thursday, August 15, 2024 By Melese E., Department of Computer Science 18
Java I/O – File I/O – Byte Oriented Streams
• If you want, you can attach the file i/o streams to other byte oriented
streams such as
• Buffered i/o streams for buffering support
• Data i/o streams for performing i/o based on Java primitive types (not only bytes)
• Object i/o streams for object serialization – which means to read and write objects to
and from a file
• In all cases,
• you need to create an object of FileInputStream for reading and FileOutputStream
for writing
• Then pass these objects to the corresponding constructors of the above classes
Thursday, August 15, 2024 By Melese E., Department of Computer Science 19
Java I/O – File I/O – Byte Oriented Streams
• Using BufferedInputStream and BufferedOutputStream
• These stream classes use a memory buffer so that
• It is allowed to do I/O operations on more than a byte at a time – thereby improving performance
• Because a buffer is available,
• Skipping – ignoring a specified number of bytes of input
• Marking, - placing a mark at the current point in the input stream that will remain valid until a
specified number of bytes are read
• and resetting (resetting the input pointer to the previously set mark) a stream become possible
• These classes has the following constructors
• BufferedInputStream(InputStream inputStream)
• BufferedInputStream(InputStream inputStream, int bufSize)
• BufferedOutputStream(OutputStream outputStream)
• BufferedOutputStream(OutputStream outputStream, int bufSize)
Thursday, August 15, 2024 By Melese E., Department of Computer Science 20
Java I/O – File I/O – Byte Oriented Streams
import [Link].*; [Link]();
class BufferedStreamDemo{ while((c=[Link]())!=-1){
public static void main(String[] args) throws IOException{
[Link]((char)c);
FileInputStream fis = new FileInputStream("[Link]");
}
BufferedInputStream bis = new BufferedInputStream(fis);
int c; [Link]();
boolean marked=false; [Link]();
while((c = [Link]())!=-1){ }
if(!marked && (char)c == ' '){ }
marked = true;
[Link](30);
}
[Link]((char)c);
}
[Link]();
Thursday, August 15, 2024 By Melese E., Department of Computer Science 21
Java I/O – File I/O – Byte Oriented Streams
• Using DataInputStream and DataOutputStream
• Helps us to perform input/output of primitive types directly
• The DataInputStream class has a method for each primitive type
• final double readDouble() throws IOException
• final boolean readBoolean( ) throws IOException
• final int readInt( ) throws IOException
• final String readUTF() throws IOException
• The DataOutputStream class has a method for each primitive type
• final void writeDouble(double value) throws IOException
• final void writeBoolean(boolean value) throws IOException
• final void writeInt(int value) throws IOException
• final void writeUTF(String value) throws IOException
• These classes have the following constructors
• DataInputStream(InputStream inputStream)
• DataOutputStream(OutputStream outputStream)
Thursday, August 15, 2024 By Melese E., Department of Computer Science 22
Java I/O – File I/O – Byte Oriented Streams
import [Link].*; [Link]([Link]());
public class DataIODemo{ [Link]([Link]());
public static void main(String[] args) throws IOException{ [Link]([Link]());
FileOutputStream fo = new FileOutputStream(“[Link]"); [Link]([Link]());
DataOutputStream dos = new DataOutputStream(fo); [Link]();
[Link](5.5f); [Link]();
[Link]('a'); }
[Link](5050L); }
[Link]("Hi there");
[Link]();
[Link]();
FileInputStream fi = new FileInputStream(“[Link]");
DataInputStream dis = new DataInputStream(fi);
Thursday, August 15, 2024 By Melese E., Department of Computer Science 23
Java I/O – File I/O – Byte Oriented Streams
• Using ObjectInputStream and ObjectOutputStream
• These classes are needed for object serialization in general
• Serialization
• Is the process of writing the state of an object to a byte stream (the stream may be file,
network, … )
• Deserialization is the reverse operation of serialization (reading the state of an object from a
stream)
• Only an object that implements the Serializable interface can be saved and restored by the
serialization facilities.
• The Serializable interface defines no members
• The ObjectInputStream and ObjectOutputStream classes have the
following constructors respectively
• ObjectInputStream(InputStream inStream) throws IOException
• ObjectOutputStream(OutputStream outStream) throws IOException
Thursday, August 15, 2024 By Melese E., Department of Computer Science 24
Java I/O – File I/O – Byte Oriented Streams
• The method of ObjectInputStream used for serialization is
• Object readObject() – reads an object
• It also has methods to read primitive types
• The method of ObjectOutputStream used for serialization is
• final void writeObject(Object obj)
• It also has methods for writing primitive types and arrays of them
Thursday, August 15, 2024 By Melese E., Department of Computer Science 25
Java I/O – File I/O – Byte Oriented Streams
import [Link]; Example e2 = new Example();
import [Link]; e2.x = 105;
import [Link]; e2.y = 3500L;
import [Link];
e2.a = 'q';
import [Link];
e2.z = 99.35f;
import [Link];
public class ObjSeri { [Link](e1);
public static void main(String[] args) throws IOException, [Link](e2);
ClassNotFoundException {
[Link]();
FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos); [Link]();
Example e1 = new Example(); FileInputStream fis = new FileInputStream("[Link]");
e1.x = 5; ObjectInputStream ois = new ObjectInputStream(fis);
e1.y = 25L; Example e3, e4;
e1.a = 'z';
e1.z = 22.5f;
Thursday, August 15, 2024 By Melese E., Department of Computer Science 26
Java I/O – File I/O – Byte Oriented Streams
e3 = (Example) [Link]();
e4 = (Example) [Link]();
[Link]();
[Link]();
[Link](e3.x + " " + e3.y + " " + e3.a + " " + e3.z);
[Link](e4.x + " " + e4.y + " " + e4.a + " " + e4.z);
}
}
class Example implements Serializable {
int x;
long y;
char a;
float z;
}
Thursday, August 15, 2024 By Melese E., Department of Computer Science 27
Java I/O – File I/O – Character Oriented Streams
• The way streams are used is similar to • Some of the important methods of Reader
that of byte oriented streams class – also shared by the subclasses
• void close()
• Create an object attached to the i/o • int read()
device – in this case the file
• int read(char[] buffer)
• Use FileReader and FileWriter classes
• Then either • Some of the important methods of the
• Use the objects of FileReader and FileWriter
Writer class – also shared by subclasses
directly or • void close()
• Attach them to other character oriented • void write(int ch)
stream classes such as • void write(char[] buffer)
• BufferedReader / BufferedWriter • void write(String st)
• The super class for all character • Some of the FileReader class constructors
oriented stream classes • FileReader(String filePath)
• FileReader(File fileObj)
• Reader – for character input stream
classes • Some of the FileWriter class constructors
• Writer – for character output stream • FileWriter(String filePath)
classes • FileWriter(File fileObj)
Thursday, August 15, 2024 By Melese E., Department of Computer Science 28
Java I/O – File I/O – Character Oriented Streams
import [Link];
import [Link];
import [Link];
public class CharOriented {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("[Link]");
[Link]('a');
[Link]("this is an example");
[Link]();
FileReader fr = new FileReader("[Link]");
int ch;
while((ch = [Link]())!=-1){
[Link]((char)ch);
}
[Link]();
}
}
Thursday, August 15, 2024 By Melese E., Department of Computer Science 29
Java I/O – File I/O – Character Oriented Streams
• Using BufferedReader and BufferedWriter
• These classes are subclass of Reader and Writer respectively, as a result, they
share methods defined in the super classes
• BufferedReader class constructor
• BufferedReader(Reader inputStream)
• BufferedWriter class constructor
• BufferedWriter(Writer outputStream)
Thursday, August 15, 2024 By Melese E., Department of Computer Science 30
Java I/O – File I/O – Character Oriented Streams
import [Link]; FileReader fr = new FileReader("[Link]");
import [Link]; BufferedReader br = new BufferedReader(fr);
import [Link]; int ch;
import [Link]; while((ch = [Link]())!=-1){
import [Link]; [Link]((char)ch);
public class BufferedCharOriented {
}
public static void main(String[] args) throws IOException {
[Link]();
FileWriter fw = new FileWriter("[Link]");
[Link]();
BufferedWriter bw = new BufferedWriter(fw);
}
[Link]('a');
}
[Link]("this is an example");
[Link]();
[Link]();
Thursday, August 15, 2024 By Melese E., Department of Computer Science 31
Java I/O – File Management
• The File class
• A File object is used to obtain or manipulate the information associated with a disk file, such
as
• the permissions, time, date, and directory path, and to navigate subdirectory hierarchies
• A directory in Java is treated simply as a File with one additional property
• a list of filenames that can be examined by the list( ) method
• The following constructors can be used to create File objects
• File(String directoryPath)
• File(String directoryPath, String filename)
• File(File dirObj, String filename)
• File(URI uriObj)
• The File class provides methods that help us to work with the properties of a file
• getName() – returns the name of the file or directory
• getPath() – returns the relative path of the file or direcotry
• getAbsolutePath() – returns the absolute path of the file or directory
• getParent() – returns the parent directory of the file or directory
• exists() – returns true if the file or directory exists and false if the file or directory does not exist
Thursday, August 15, 2024 By Melese E., Department of Computer Science 32
Java I/O – File Management
• The File class (continued)
• canWrite() – returns true if the file is writeable and false if not
• canRead() – returns true if the file is readable and false otherwise
• isDirectory() – returns true if the file is a directory and false other wise
• isFile() – returns true if the file object represents a file and false otherwise
• isAbsolute() – returns true if the path specified is absolute path and false otherwise
• lastModified() – returns the number of milliseconds from 00:00:00 GMT, January 1, 1970 up to the
last time the file was modified
• length() – returns the length of the file in bytes
• renameTo(File newName) – renames the file into a new filename; returns true if successful and
false if not
• delete() – deletes the file and returns true if successful and false if not
• All the above methods are used to work with both file and directory
Thursday, August 15, 2024 By Melese E., Department of Computer Science 33
Java I/O – File Management
• The File class (continued)
• There are special methods to be used with directories only
• String[] list() – returns the names of files and directories in the directory
• File[] listFiles() – returns the same as list() but in the form of the File object
• mkdir() – creates a directory for which the path is known and returns true if successful
and false otherwise
• mkdirs() – create all the directories along the path specified and returns true if successful
and false otherwise
• The following program demonstrates the use of the File class to work with the
properties of files and directories
Thursday, August 15, 2024 By Melese E., Department of Computer Science 34
Java I/O – File Management
import [Link]; File f2 = new File("one/two/three/", "four");
public class FileDemo{ if(![Link]())
public static void main(String[] args){
[Link]();
File f = new File("[Link]");
}
[Link]([Link]());
[Link]([Link]()); }
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
File f1 = new File("abebe");
if(![Link]())
[Link]();
Thursday, August 15, 2024 By Melese E., Department of Computer Science 35
The End!
Thursday, August 15, 2024 By Melese E., Department of Computer Science 36