11/13/2025
Java File Handling
and I/O Streams
Contents
Java File/Directory Handling
Java I/O Streams
1
11/13/2025
Java File/Directory
Handling
Java File/Directory Handling
Class [Link]
The class [Link] can represent either a file or a directory.
A path string is used to locate a file or a directory.
Unfortunately, path strings are system dependent, e.g.,
"c:\myproject\java\[Link]" in Windows or
"/myproject/java/[Link]" in Unix/Mac.
2
11/13/2025
Java File/Directory Handling
Windows use back-slash '\' as the directory separator; while Unixes/Mac use
forward-slash '/'.
Windows use semi-colon ';' as path separator to separate a list of paths; while
Unixes/Mac use colon ':'.
Windows use "\r\n" as line delimiter for text file; while Unixes use "\n" and Mac
uses "\r".
The "c:\" or "\" is called the root. Windows supports multiple roots, each maps to
a drive (e.g., "c:\", "d:\"). Unixes/Mac has a single root ("\").
Java File/Directory Handling
A path could be absolute (beginning from the root) or relative (which is
relative to a reference directory).
Special notations "." and ".." denote the current directory and the parent
directory, respectively.
// A file relative to the current working directory
File file = new File("[Link]");
File file = new File("d:\\myproject\\java\\[Link]");
// A file with absolute path
File dir = new File("c:\\temp"); // A directory
3
11/13/2025
Verifying Properties of a File/Directory
public boolean exists() // Tests if this file/directory exists.
public long length() // Returns the length of this file.
public boolean isDirectory() // Tests if this instance is a directory.
public boolean isFile() // Tests if this instance is a file.
public boolean canRead() // Tests if this file is readable.
public boolean canWrite() // Tests if this file is writable.
public boolean delete() // Deletes this file/directory.
public void deleteOnExit() // Deletes this file/directory when the program terminates.
public boolean renameTo(File dest) // Renames this file.
public boolean mkdir() // Makes (Creates) this directory.
List Directory
4
11/13/2025
Create a File
In Java, you can create a new file with the createNewFile() method
from the File class.
This method returns:
•true - if the file was created successfully
•false - if the file already exists
Note that the method is enclosed in a try...catch block. This is
necessary because it throws an IOException if an error occurs (if the file
cannot be created for some reason):
10
Java File/Directory Handling
10
5
11/13/2025
11
Java Write To Files
11
12
Java Read Files
12
6
11/13/2025
13
Delete a File
To delete a file in Java, use the delete() method:
13
Java I/O Streams
14
7
11/13/2025
15
Java I/O Streams
In Java, there is an important difference between working with the File class and working
with I/O Streams (Input/Output Stream):
•The File class (from [Link]) is used to get information about files and directories:
• Does the file exist?
• What is its name or size?
• Create or delete files and folders
•But: the File class does not read or write the contents of the file.
So far, we have used FileWriter for writing text and Scanner for reading text. These are
easy to use, but they are mainly designed for simple text files.
I/O Streams are more flexible, because they work with text and binary data (like images,
audio, PDFs).
15
16
Types of Streams
Byte Streams
Work with raw binary data (like images, audio, and PDF files).
Examples: FileInputStream, FileOutputStream.
Character Streams
Work with text (characters and strings). These streams automatically handle
character encoding.
Examples: FileReader, FileWriter, BufferedReader, BufferedWriter.
Use character streams when working with text, and byte streams when working
with binary data.
16
8
11/13/2025
17
Java I/O Streams
Programs read inputs from data sources (e.g., keyboard, file, network,
memory buffer, or another program) and write outputs to data sinks
(e.g., display console, file, network, memory buffer, or another
program).
In Java standard I/O, inputs and outputs are handled by the so-
called streams. A stream is a sequential and contiguous one-way flow
of data (just like water or oil flows through the pipe).
17
18
Java I/O Streams
18
9
11/13/2025
19
Byte-Based I/O Streams
Byte streams are used to
read/write raw
bytes serially from/to an
external device.
All the byte streams are
derived from
the abstract superclasses Inp
utStream and OutputStream
, as illustrated in the class
diagram.
19
20
Opening & Closing I/O Streams
20
10
11/13/2025
21
Layered (or Chained) I/O Streams
The I/O streams are often layered or
chained with other I/O streams, for
purposes such as buffering, filtering,
or data-format conversion (between
raw bytes and primitive types).
For example, we can layer
a BufferedInputStream to
a FileInputStream for buffered input,
and stack a DataInputStream in front
for formatted data input (using
primitives such as int, double), as
illustrated in the following diagrams.
21
22
Buffered I/O Byte-Streams
The read()/write() method in InputStream/OutputStream are
designed to read/write a single byte of data on each call. This is grossly
inefficient, as each call is handled by the underlying operating system
(which may trigger a disk access, or other expensive operations).
Buffering, which reads/writes a block of bytes from the external device
into/from a memory buffer in a single I/O operation, is commonly
applied to speed up the I/O.
22
11
11/13/2025
23
Java I/O Streams
FileInputStream/FileOutputStream is not buffered. It is often chained
to a BufferedInputStream or BufferedOutputStream, which provides
the buffering.
23
24
Example 1: Copying a file byte-by-byte without
Buffering.
import [Link].*;
public class FileCopyNoBuffer { // Pre-JDK 7
public static void main(String[] args) {
String inFileStr = "[Link]";
String outFileStr = "[Link]";
FileInputStream in = null;
FileOutputStream out = null;
long startTime, elapsedTime; // for speed benchmarking
// Print file length
File fileIn = new File(inFileStr);
[Link]("File size is " + [Link]() + "
bytes");
24
12
11/13/2025
25
Example 1: Copying a file byte-by-byte without
Buffering.
try {
in = new FileInputStream(inFileStr);
out = new FileOutputStream(outFileStr);
startTime = [Link]();
int byteRead;
// Read a raw byte, returns an int of 0 to 255.
while ((byteRead = [Link]()) != -1) {
// Write the least-significant byte of int, drop the upper 3 bytes
[Link](byteRead);
}
elapsedTime = [Link]() - startTime;
[Link]("Elapsed Time is " + (elapsedTime / 1000000.0) + " msec");
} catch (IOException ex) {
[Link]();
25
26
Example 1: Copying a file byte-by-byte without
Buffering.
} finally { // always close the I/O streams
try {
if (in != null) [Link]();
if (out != null) [Link]();
} catch (IOException ex) {
[Link]();
}
}
}
}
26
13
11/13/2025
Example 2: Copying a file with a Programmer- 27
Managed Buffer.
import [Link].*;
public class FileCopyUserBuffer { // Pre-JDK 7
public static void main(String[] args) {
String inFileStr = "[Link]";
String outFileStr = "[Link]";
FileInputStream in = null;
FileOutputStream out = null;
long startTime, elapsedTime; // for speed benchmarking
// Check file length
File fileIn = new File(inFileStr);
[Link]("File size is " + [Link]() + "
bytes");
27
28
Example 2: Copying a file with a Programmer-
Managed Buffer.
try {
in = new FileInputStream(inFileStr);
out = new FileOutputStream(outFileStr);
startTime = [Link]();
byte[] byteBuf = new byte[4096]; // 4K byte-buffer
int numBytesRead;
while ((numBytesRead = [Link](byteBuf)) != -1) {
[Link](byteBuf, 0, numBytesRead);
}
elapsedTime = [Link]() - startTime;
[Link]("Elapsed Time is " + (elapsedTime / 1000000.0) + "
msec");
} catch (IOException ex) {
[Link]();
28
14
11/13/2025
29
Example 2: Copying a file with a Programmer-
Managed Buffer.
} finally { // always close the streams
try {
if (in != null) [Link]();
if (out != null) [Link]();
} catch (IOException ex) { [Link](); }
}
}
}
29
30
Write a Text File (Basic Example)
30
15
11/13/2025
31
Append to a File
By default, FileOutputStream overwrites the file if it already exists. To add (append) new
content instead, pass true as the second argument.
31
32
BufferedReader and BufferedWriter
BufferedReader and BufferedWriter make reading and writing text files faster.
•BufferedReader lets you read text line by line with readLine().
•BufferedWriter lets you write text efficiently and add new lines with newLine().
These classes are usually combined with FileReader and FileWriter, which handle
opening or creating the file. The buffered classes then make reading/writing faster by
using a memory buffer.
32
16
11/13/2025
33
Read a Text File (Line by Line)
33
34
Write to a Text File
Use BufferedWriter with FileWriter to write text to a file. The write() method
adds text, and you can use newLine() to insert a line break:
34
17
11/13/2025
35
Append to a Text File
To add new content to the end of a file (instead of overwriting), pass true to FileWriter:
35
18