AMiT
Program:
Computer
Science
G3 – CS
Java Programming
Instructor:
Addisu M. (Asst.
Prof)
2
Ch hre
rT
Streams & File I/O
ap e
te
3
Outline
0 Overview of Streams
and File I/O Classes
10
File and FileDialog
Java Programming
objects
2
0 Object I/O with Object
Streams
30
File Management
4
Introduction
Jan 9, 2026
I/O = Input/Output
Input can be from keyboard or a file
Output can be to display (screen) or a file
[Link] package contains all classes required for
input and output operations
Advantages of file I/O
permanent copy
Java Programming
output from one program can be input to another
input can be automated (rather than entered
manually)
Streams are sequences/flow of data
support many different kinds of data, including
characters, numbers, bytes consisting of binary 4
Introduction
Jan 9, 2026
Files can be classified as either text or binary
Human readable files are text files
Data stored in a text files is represented in
human readable form
All other files are binary files
Data stored in a binary files is represented in
binary form
Java Programming
Java provides many classes for performing text
I/O and binary I/O
It uses the concept of stream to make I/O
operation fast
In order to perform I/O, you need to create
objects using appropriate Java I/O classes 5
Introduction
Jan 9, 2026
• Text files: bits represent printable characters
a file can be created and/or opened by text editor
(Notepad) and read by humans easily
Everything in the file is character form. We can
think of the file as one long string, even if it is
organized into lines.
Binary files: bits represented in binary form, such
Java Programming
•
as executable instructions or numeric data
Cannot be directly or conveniently viewed or edited
For by
Example
humans
• Java source programs are stored in text files and can
be read by a text editor, but Java .class files are
stored in binary files and are read by JVM (Java 6
Introduction
Jan 9, 2026
Advantage of binary files are more efficient to
process than text files, because
Binary file I/O does not require encoding &
decoding, but
Text file I/O requires encoding and decoding
E.g., number 123 is smaller in binary than in text:
"123"
Text file consists of a sequence of characters
Java Programming
E.g:, decimal integer 199 is stored as sequence of
3 characters: '1', '9', '9' in text file
Java is UTF-16, that is uses 2 bytes variable
encoding for characters
'1', '9', '9' would require 6 bytes to encode it
Binary file consists of a sequence of bits
E.g, decimal integer 199 is stored as one byte 7
File Operations
Jan 9, 2026
[Link] is the central class that works
with files and directories
instance of this class represents
name of a file or directory on the host file
system
Java Programming
When a File object is created, the system
doesn't check to the existence of a
corresponding file/directory
If the file exists, a program can examine its
attributes and perform various operations on 8
File Operations
Jan 9, 2026
File
Constructors
Constructor Description
File(File creates a new File instance from a
parent, parent abstract pathname and a child
String child) pathname string
File(String creates a new File instance by
converting the given pathname string
Java Programming
pathname) into an abstract pathname
File(String creates a new File instance from a
parent, parent pathname string and a child
String child) pathname string
creates a new File instance by
File(URI uri) converting the given file: URI into an 9
abstract pathname
File Operations
Jan 9, 2026
Modifier Method Description
and
Type
boolean createNewFi It atomically creates a new, empty file named by this
File Methods
le() abstract pathname if and only if a file with this name
does not yet exist.
boolean canWrite() It tests whether the application can modify the file
denoted by this abstract [Link][]
boolean canExecute( It tests whether the application can execute the file
Java Programming
) denoted by this abstract pathname.
boolean canRead() It tests whether the application can read the file
denoted by this abstract pathname.
boolean isDirectory() It tests whether the file denoted by this abstract
pathname is a directory.
boolean isFile() It tests whether the file denoted by this abstract
pathname is a normal file.
String getName() It returns the name of the file or directory denoted 10
File Operations
Jan 9, 2026
We can perform the following operation
on a file:
Java Programming
11
File Operations
Jan 9, 2026
Create a File
use createNewFile() method of file - returns
true when it successfully creates new file and
false when the file already exists
File f = new File("[Link]");
Java Programming
This won’t create any physical file, first it will
check the availability of physical file with [Link]
or not
If it is already available then f pointing to that file
If it is not available this line won’t create any
physical file and just it creates java file object to 12
File Operations
Jan 9, 2026
import [Link];
import [Link]; // class for handling errorsCreate a
class CreateFile {
public static void main(String args[]) {
File
try {
File f0 = new File("[Link]");
if ([Link]()) {
[Link]([Link]() + " is created
successfully.");
Java Programming
} else {
[Link]("File is already exist in the di
rectory.");
}
} catch (IOException ex) {
[Link]("An unexpected error is occurred.");
[Link](); 13
File Operations
Jan 9, 2026
Get File Information
use several methods to get the information about
the file like name, absolute path, is readable, is
writable and length
Description:
we import [Link] package
Java Programming
get the name of the file using getName()
get the path of file
using getAbsolutePath() method of file
check whether to write data into a file or not
using canWrite()
check whether to read the data of the file or not
14
using canRead()
File Operations
Jan 9, 2026
Get File Information
import [Link];
class FileInfo {
public static void main(String[] args) {
File f0 = new File("D:[Link]"); // Creating file objec
t
if ([Link]()) {
Java Programming
[Link]("The name of the file is: " + [Link]());
[Link]("The absolute path of the file is: " + [Link]
ePath();
// Checking whether the file is writable or not
[Link]("Is file writeable?: " + [Link]());
// Checking whether the file is readable or not
15
File Operations
Jan 9, 2026
Write to a File
use FileWriter class and its write() method together
import [Link];
import [Link];
class WriteToFile {
public static void main(String[] args) {
try {
Java Programming
FileWriter fw = new FileWriter("D:[Link]");
[Link](“Writing the content into the File.");
[Link]();
[Link]("Content is successfully wrote to the file.");
}
catch (IOException e) {
[Link]("Unexpected error occurred");
[Link](); 16
}
File Operations
Jan 9, 2026
Read from a File
to write data into a file, use the Scanner class
create an instance of Scanner class and use
hasNextLine() & nextLine() methods to get data
from the file
import [Link];
import [Link]; // handling error
Java Programming
s
import [Link]; // for reading text files
class ReadFromFile {
public static void main(String[] args) {
try {
17
File Operations
Jan 9, 2026
Read from a File
while ([Link]()) {
String fileData = [Link]();
[Link](fileData);
Java Programming
}
[Link]();
} catch (FileNotFoundException exception) {
[Link]("Unexcpected error occurred!");
[Link](); 18
File Operations
Jan 9, 2026
Delete a File
use delete() method of the file
don’t expected to close the stream
using close() method because we neither use
import [Link];
FileWriter class nor Scanner class
class DeleteFile {
public static void main(String[] args) {
Java Programming
File f0 = new File("D:[Link]");
if ([Link]()) {
[Link]([Link]()
+ " file is deleted successfully.");
} else {
[Link]("Unexpected error found in deletion of the
file.") 19
Directories
Jan 9, 2026
Directory – organizing structure of the
computer file system
File organization structure is a hierarchical
structure involving parent and child
relationships just like tree data structures
Java Programming
20
Directories
Jan 9, 2026
Directory – contain a list of other files and
directories
use File object to create directory & list down
files available in a directory
Creating Directories
mkdir() - creates a directory
useful File utility methods – used to create
returning true on success and false on failure
Java Programming
directories
Failure indicates that the path specified in the
File object already exists, or that the directory
cannot be created because the entire path does
not exist yet
mkdirs() - creates both directory and all parents
of the directory, including necessary and non- 21
Directories
Jan 9, 2026
Creating Exampl
import [Link]; e
Directories
public class CreateDir {
public static void main(String args[]) {
String dirname = "D:\\Educational\\Adv Prog";
File d = new File(dirname); // Create directory now
Java Programming
if ([Link]()) { [Link]("Directory is
created"); }
else { [Link]("Directory cannot be
created"); }
}
}
22
Directories
Jan 9, 2026
Listing Directories
use list( ) method provided by File object to
try {
list down all files and directories available in
File fl = new File(" D:\\Educational");
a directory
if([Link]()){
String[] lists = [Link](); // array of files and
directory
array of file
Java Programming
names
for(String li:lists) {// for each name in the path
array
[Link](li); // prints file names
}
}
}
23
catch (Exception e) { [Link](); // if any error
Directories
Jan 9, 2026
Listing Directories
use list( ) method provided by File object to
list down all files and directories available in
try {
a
Filedirectory
fl = new File("D:\\Educational");
pathname
if([Link]()){
File[] files = [Link](); // array of file paths
Java Programming
for(File f:files){// for each name in the path array
[Link]([Link]()); //prints
array of
array of pathnames
s
}
}
}
catch (Exception e) { [Link](); // if any error
occurs }
24
Streams
Jan 9, 2026
• Stream is a sequence of data that is read from
source and write to destination
A program uses an input
stream to read data from a
source, one item at a time
Java Programming
A program uses an output
stream to write data to a 25
Streams
Jan 9, 2026
Standard I/O
All the programming languages provide support for
standard I/O where user's program can take input
from a keyboard and then produce an output on
computer screen
Java provides the following three standard streams:
Standard Input - used to feed data to user’s program
Java Programming
and usually a keyboard is used as standard input
stream & represented as [Link].
Standard Output - used to output the data produced
by the user’s program and usually a computer screen is
used for standard output stream and represented as
[Link] 26
Streams
Jan 9, 2026
Standard:
import [Link].*;
Example
class Main {
public static void main(String[] args) {
[Link]("Enter your name: ");
// takes input from keyboard
Java Programming
String name =
[Link]().readLine();
//prints the name
[Link]("My name is " +
name);
} 27
Types of Streams
Java Programming Jan 9, 2026
28
Types of Streams
Jan 9, 2026
Byte Stream: used to read & write single byte (8
bits) of data, can handle any kind of data like Text,
Audio, Video, Images etc, further classified into two
– root classes
The perspective is the program. (Do not confuse
direction as if it's from the file)
InputStream: used to read data from various input
Java Programming
devices like keyboard, file, network, etc
stream coming from the file into the program
OutputStream: used to write data to various output
devices
stream going into the file from the program
Character Stream: used to read & write a 16 bit
Unicode of data, can handle text data only 29
Types of Streams: Byte
Java Programming Jan 9, 2026
30
Types of Streams: Byte
Jan 9, 2026
FileInputStream Class
used for reading data (in bytes) from the files
extends the InputStream abstract class
public class FileInputStream extends I
nputStream
Create an FileInputStream
we must import [Link]
Java Programming
package first
[Link]
Using the path toinput
file = new
FileInputStream(stringPath);
FileInputStream
2. Using an objectinput = new
of the file FileInputStream(File
fileObject);
All methods in FileInputStream are inherited from 31
Types of Streams: Byte
Jan 9, 2026
FileInputStream Class
read() - reads one byte of data from the input
Methods
stream - implemented by its subclasses
read(byte[] array) - reads bytes from the
stream and stores in the specified array
available() - returns # of bytes available in the
input stream
close() - to close the file input stream. Once the
Java Programming
close() method is called, we cannot use input
stream to read data
finalize() - ensures that the close() method is
called
mark() - marks the position in the input stream
up to which data has been read
reset() - returns the control to the point in the 32
Types of Streams: Byte
Jan 9, 2026
read() met
FileInputStream Class
import [Link]; hod
public class Main {
public static void main(String args[]) {
try {
FileInputStream input = new
FileInputStream("[Link]");
[Link]("Data in the file: ");
int i = [Link](); // Reads the first byte
Java Programming
while(i != -1) {
[Link]((char)i);
i = [Link](); // Reads next byte from the
file
}
[Link]();
}
catch(Exception e) { [Link](); }
} 33
Types of Streams: Byte
Jan 9, 2026
FileOutputStream Class
used to write data (in bytes) to the files
Syntax
1. Using the path to file
FileOutputStream fos = new FileOutputStream(fileName);
//This Syntax will overwrite the contents.
FileOutputStream fos = new FileOutputStream(String
Java Programming
path, boolean value);
//ThisSyntax will append the contents
value is an optional boolean parameter
If it is set to true, new data will be appended to
the end of the existing data in the file
Otherwise, new data overwrites the existing data in
the file
2. Using an object
FileOutputStream output of the file
= new 34
FileOutputStream(File fileObject);
Types of Streams: Byte
Jan 9, 2026
FileOutputStream Class
write() - writes the single byte to the file output
Methods – implemented by its subclasses
stream
write(byte[] array) - writes the bytes from the
specified array to the output stream
write(byte[] array, int start, int length) -
writes the number of bytes equal to length to the
Java Programming
output stream from an array starting from the
position start
flush() - to clear the output stream – forces the
output stream to write all data present in output
stream to the destination
close() - to close the file output stream. Once the 35
Types of Streams: Byte
Jan 9, 2026
write() met
FileOutputStream Class
import [Link].*; hod
class Filecopy{
public static void main(String[] args)
throws Exception{
FileInputStream fis = new
FileInputStream(“[Link]”);
FileOutputStream fos = new
Java Programming
FileOutputStream(“[Link]”, true);
int ch;
while((ch = [Link]())! = -1){
[Link](ch);
}
[Link]();
[Link]();
} 36
Types of Streams:
Character
Jan 9, 2026
Java Programming
37
Types of Streams:
Character
Jan 9, 2026
Character Stream: used to read & write 16-bit
Unicode characters/sequence of characters
can handle only text, also called as Text Streams
There are many classes but the most frequently
used classes
FileReader: similar to Input Streams performing
Java Programming
reading operations
FileWriter: similar to output Streams performing
writing operations
Internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream
Major difference is that FileReader reads and 38
Types of Streams:
Character
Jan 9, 2026
FileReader Class
used to read contents of a file
Two most commonly used constructors
FileReader(String filePath) – gets filename in string
FileReader(File fileObj) – gets filename
in file instance
For both – opens the given file in read mode. If file
Java Programming
FileReader
doesn't fr=new
exist, it throws FileReader("D:\\
FileNotFoundException
[Link]");
int i;
while((i=[Link]())!=-1) {
[Link]((char)i);
} 39
Types of Streams:
Character
Jan 9, 2026
FileWriter Class
Creates a Writer that you can use to write
to a file
Its most commonly used constructors are
FileWriter(String filePath)
FileWriter(String
Java Programming
filePath, boolean append)
FileWriter(String fileObj)
FileWriter(String fileObj, boolean append)
They throw an IOException
40
Types of Streams:
Character
Jan 9, 2026
FileWriter Class
import [Link].*;
class FileWriterDemo{
public static void main(String[] args)
throws Exception{
Striing source = “This is FileWriter
Java Programming
demo”;
FileWriter fw0 = new
FileWriter(“[Link]”);
[Link](source); 41
Exception Handling with
File I/O
Jan 9, 2026
Catching IOExceptions
• IOException is a predefined class
• File I/O might throw an IOException
• catch the exception in a catch block that at
least prints an error message and ends the
program
Java Programming
• FileNotFoundException is derived from
IOException
any catch block that catches IOExceptions also
catches FileNotFoundExceptions
put the more specific one first (the derived one) so
it catches specifically file-not-found exceptions 42
Exception Handling with
File I/O
Jan 9, 2026
Example: Reading File Name from
Keyboard
public static void main(String[] args)
{
String fileName = null; // outside try block, can be used
in catch
try
Java Programming
using file{ reading file
name read name from
Scanner keyboard = new Scanner([Link]);
from the keyboard
[Link]("Enter file name:");
keyboard
fileName = [Link]();
reading BufferedReader inputStream =
data from new BufferedReader(new
the FileReader(fileName));
file 43
Exception Handling with
File I/O
Jan 9, 2026
Example: Reading File Name from
Keyboard
[Link](line);
// . . . code for reading second line not shown
closing the file
here . . .
[Link]();
}
Java Programming
catch(FileNotFoundException e)
{
[Link]("File " + filename + " not
found.");
}
catch(IOException e)
44
{
Exception Handling with
File I/O
Jan 9, 2026
[Link]()
to get detailed message of the error
try
{
…
}
Java Programming
catch (FileNotFoundException e)
{
[Link](filename + “ not found”);
[Link](“Exception: “ + [Link]());
} 45
46
THANKS
!
Questions,
Ambiguities,
Doubts, … ???