Streams & Files
Vũ Thị Hồng Nhạn
(vthnhan@[Link])
Dept. of Software Engineering,
Faculty of Information Technology, UET
Vietnam National Univ., Hanoi
Contents
I/O streams
Files & streams
File class
Serialize java objects
Creating, writing, reading randomly/sequentially a random-
access file
11/3/2025 Streams Page 2
I/O streams
A stream is a sequence of data
Streams support various types of data, including bytes, primitive data types,
characters, and objects
An I/O stream represents various types of sources & destinations (e,g. disk files,
devices, other programs)
A program uses an Input stream to read data from a source, one item at a time
Similarly, a program uses an Output stream to write data to a destination, one item at a
time
11/3/2025 Streams Page 3
Byte streams
Programs use byte streams to perform input & output of 8-bit bytes
All byte stream classes are derived from InputStream and OutputStream
Hierarchy of InputStream
11/3/2025 Streams Page 4
Byte streams…
Hierarchy of OutputStream
11/3/2025 Streams Page 5
Byte streams…
InputStream
int read()
Reads a single byte of data from the input stream
Return the byte read, or -1 if the end of the stream is reached
int read(byte buf[])
Reads data into the provided array (buf)
Returns the number of bytes read, or -1 if the end of the stream is reached
int read(byte buf[], int offset, int length)
Reads up to length bytes of data into the provided array buf, starting at the
specified offset in the array
void close()
11/3/2025 Streams Page 6
Byte streams…
OutputStream
int write(int c)
int write(byte buf[])
int write(byte buf[], int offset, int length)
void close()
void flush()
11/3/2025 Streams Page 7
Byte streams…
Example 1
Write a program using byte streams to copy a text file to another file
Copy one byte at a time
Apply FileInputStream & FileOutputStream for the file I/O
byte streams
11/3/2025 Streams Page 8
Example 1…
import [Link];
import [Link];
import [Link];
public class CopyBytes{
public static void main(String[] args) throws IOException{
FileInputStream in=null;
FileOutputStream out = null;
try{
in = new FileInputStream(“[Link]”);
out = new FileOutputStream(“[Link]”);
int c;
While((c = [Link]())!= -1 ){ //c holds a byte value in its
lass 8 bits
[Link](c);
}
}finally{
if( in !=null) { [Link](); }
if ( out !=null ) { [Link](); }
}
}
}
11/3/2025 Streams Page 9
When not to use Byte streams
The previous program represents a kind of low-level I/O that you
should avoid
Because [Link] contain character data, the best approach is to use
character streams
Actually, all other stream types are built on byte streams
11/3/2025 Streams Page 10
Character streams
All character stream classes are derived from Reader and Writer
Similar to byte streams, these character stream classes are
specialized for file input and file output operations, specially
FileReader and FileWriter
11/3/2025 Streams Page 11
Character streams…
Hierarchy of Reader
11/3/2025 Streams Page 12
Character streams…
Hiearchy of Writer
11/3/2025 Streams Page 13
Character streams…
Reader
int read()
int read(char buf[])
int read(char buf[], int offset, int length)
void close()
11/3/2025 Streams Page 14
Character streams…
Writer
int write(int c)
int write(char buf[])
int write(char buf[], int offset, int length)
void close()
void flush()
11/3/2025 Streams Page 15
Example 2
import [Link];
import [Link];
import [Link];
public class CopyCharacters{
public static void main(String[] args) throws IOException{
FileReader in = null; FileWriter out = null;
try{
in = new FileReader(“[Link]”);
out = new FileWriter(“[Link]”);
char c;
while( (c=[Link]())!= -1){ //c holds a character value in
its last 16 bits
[Link](c);
}
}
finally{
if( in !=null ){ [Link](); }
if( out !=null) { [Link]();}
}
}
}
11/3/2025 Streams Page 16
Buffered streams
The examples mentioned use unbuffered I/O, i.e.
Each read or write request is handled directly by the underlying OS
make a program much less efficient!
Since each request often triggers each disk access, network activity, or some other
relatively expensive operation
Java platform implements buffered I/O streams
Buffered input streams read data from memory area into a buffer
Buffered output streams write data to a buffer
A program can convert an unbuffered stream into a buffered stream using
the wrapping idiom, e.g., previous example can modified as…
in = new BufferedReader(new FileReader([Link]))
out = new BufferedWriter(new FileWriter([Link]))
11/3/2025 Streams Page 17
Scanning
Objects of type of Scanner
breaking down formatted input into tokens
& translating individual tokens according to their
data type
By default, a scanner uses white space (blanks,
tabs, line terminators) to separate tokens
To use a different token separator, invoke
useDelimiter()
e.g., use the comma as the token separator
[Link](“,\\s*”); //Scanner s
11/3/2025 Streams Page 18
Example 1
11/3/2025 Streams Page 19
Example 2
11/3/2025 Streams Page 20
I/O from the command line
• Java platform support interaction through the
command line
• Standard streams
Standard streams
Java platform supports 3 standard streams
Standard input: accessed through [Link]
Standard output: [Link]
Standard error: [Link]
These objects are defined automatically and don’t need to be opened
They are byte streams (not character streams)
[Link] and [Link] are defined as PrintStream objects
To use standard input as a character stream, wrap [Link] in
InputStreamReader
InputStreamReader cin = new InputStreamReader([Link])
11/3/2025 Streams Page 22
Example
InputStreamReader reader = new InputStreamReader([Link]);
BufferedReader in = new BufferedReader(reader);
String s;
try {
s = [Link]();
}
catch (IOException e) {
...
}
11/3/2025 Streams Page 23
File
[Link] class in java
File class is an abstract representation of file and directory path
name
A path name can be absolute or relative
File class has several methods for working with files and
directories, e.g.,
creating new files or directories
deleting and renaming files or directories
listing the contents of a directory
11/3/2025 Streams Page 25
E.g. create a file Object
try{
File file = new File(“C:/Users/vthnhan/Desktop/test”);
if([Link]()){….} //new file is created
else … //file already exists
}catch(IOException e){ [Link]() }
Define an abstract file name for the test file in the directory
C:/Users/vthnhan/Desktop/
11/3/2025 Streams Page 26
Constructors
File(String pathname)
Creates a new File instance by converting the given pathname string into an
abstract pathname.
File(File parent, String child)
Creates a new File instance by combining a parent directory with a child path
File parentDir = new File("C:/Users/username/Documents");
File file = new File(parentDir, "[Link]");
File(String parent, String child)
Creates a new File instance by combining a parent path with a child path
File file = new File("C:/Users/username/Documents", "[Link]");
File(URI uri)
Creates a new File instance from a URL object, specified one with a file scheme
URI uri = new URI("[Link] File
file = new File(uri);
11/3/2025 Streams Page 27
Methods
Files
String getName()
String getPath()
String getAbsolutePath()
String getParent()
boolean renameTo(File newName)
Check if the file..
boolean exists()
boolean canWrite()
boolean canRead()
boolean isFile()
boolean isDirectory()
boolean isAbsolute()
Directory
boolean mkdir()
String[] list()
…..
11/3/2025 Streams Page 28
File handling using FileWriter & FileReader
are used to read and write data from text files
they are Character stream classes
FileReader class inherited from InputStreamReader class
for reading streams of characters
BufferedReader can be used (readLine()read a line of text
FileWriter class inherited from OutputStreamWriter class
for writing streams of characters
BufferedWriter can be used to improve speed of execution
PrintWriter used to write a line (with methods print() &
println())
11/3/2025 Streams Page 29
E.g 1. read a file
File file = new File(”[Link]”);
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
String s;
try {
s = [Link]();
}
catch (IOException e) {
...
}
11/3/2025 Streams Page 30
E.g 1. read a file…
import [Link];
import [Link];
import [Link];
import [Link];
public class Reading {
public void read(BufferedReader in) {
String s;
try {
while ((s = [Link]()) != null) {
[Link](s); // Print each line from the file
}
} catch (IOException e) {
[Link]("An error:" + [Link]());
}
}
public void doSomething() {
[Link]("Performing some other actions...");
}
}
11/3/2025 Streams Page 31
E.g 1. read a file…
public static void main(String[] args) {
File file = new File("[Link]");
try (FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader)) {
Reading o = new Reading();
[Link](in);
[Link]();
} catch (IOException e) {
[Link]("An error:" + [Link]());
}
}
11/3/2025 Streams Page 32
E.g 2. write text to a file
// Class Abc with a method to write to a PrintWriter
class Writing {
private String s = "Hello from Abc";
public void write(PrintWriter out) {
[Link](s);
[Link]();
}
public String write() {
StringBuilder buf = new StringBuilder();
[Link]("Hello from Writing\n");
[Link]("Additional data...\n");
return [Link]();
}
}
11/3/2025 Streams Page 33
E.g 2. write text to a file…
public static void main(String[] args) {
File file = new File("[Link]");
PrintWriter out = null;
try {
FileWriter writer = new FileWriter(file);
out = new PrintWriter(writer);
String s = "Hello";
// Write the string to the file
[Link](s);
} catch (IOException e) {
[Link]("An I/O error: " + [Link]());
} finally {
if (out != null) {[Link]();}
}
}
11/3/2025 Streams Page 34
E.g 1. File copy
import [Link].*;
public class CopyFile {
public static void main(String args[]) {
try {
FileReader src = new FileReader(args[0]);
BufferedReader in = new BufferedReader(src);
FileWriter des = new FileWriter(args[1]);
PrintWriter out = new PrintWriter(des);
String s;
s = [Link]();
while (s != null) {
[Link](s);
s = [Link]();
}
[Link]();
[Link]();
}
catch (IOException e) { [Link](); }
}
}
11/3/2025 Streams Page 35
Sequential access text file
Read data
FileInputStream: read data from a file
DataInputStream: read data of primitive data types
ObjectInputStream: read objects
Write data
FileOutputStream: write data to a file
DataOutputStream: write primitive data
ObjectOutputStream: write objects
11/3/2025 Streams Page 36
DataInputStream/DataOutputStream
DataInputStream: read primitive data
readBoolean, readByte, readChar, readShort,
readInt, readLong, readFloat, readDouble
DataOutputStream: write primitive data
writeBoolean, writeByte, writeChar, writeShort,
writeInt, writeLong, writeFloat, writeDouble
11/3/2025 Streams Page 37
Write primitive data sequentially
import [Link].*;
public class TestDataOutputStream {
public static void main(String args[]) {
int a[] = {2, 3, 5, 7, 11};
try {
FileOutputStream fout = new FileOutputStream(args[0]);
DataOutputStream dout = new DataOutputStream(fout);
for (int i=0; i<[Link]; i++)
[Link](a[i]);
[Link]();
}
catch (IOException e) {
[Link]();
}
}
}
11/3/2025 Streams Page 38
Read primitive data sequentially
import [Link].*;
public class TestDataInputStream {
public static void main(String args[]) {
try {
FileInputStream fin = new FileInputStream(args[0]);
DataInputStream din = new DataInputStream(fin);
while (true) {
[Link]([Link]());
}
}
catch (EOFException e) {}
catch (IOException e) {[Link]();
}
}
}
11/3/2025 Streams Page 39
Read/write objects sequentially
To save a Java object to a database or transfer it over a network
We need to convert the state of an object into a byte stream by
using Serialization
To make a java object serializable, we need to implement a marker
interface
[Link]
11/3/2025 Streams Page 40
Read/write objects sequentially
Example
import [Link];
class Record implements Serializable {
private String name;
private float score;
public Record(String s, float sc) {
name = s;
score = sc;
}
public String toString() {
return "Name: " + name + ", score: " + score;
}
}
11/3/2025 Streams Page 41
Example 1: write objects
import [Link].*;
public class TestObjectOutputStream {
public static void main(String args[]) {
Record r[] = { new Record("john", 5.0F),
new Record("mary", 5.5F),
new Record("bob", 4.5F) };
try {
FileOutputStream fout = new FileOutputStream(“[Link]”);
ObjectOutputStream out = new ObjectOutputStream(fout);
for (int i=0; i<[Link]; i++)
[Link](r[i]);
[Link]();
}
catch (IOException e) {[Link](); }
}
}
11/3/2025 Streams Page 42
Example 2: read objects
import [Link].*;
public class TestObjectInputStream {
public static void main(String args[]) {
Record r;
try {
FileInputStream fin = new FileInputStream( “[Link]”);
ObjectInputStream in = new ObjectInputStream(fin);
while (true) {
r = (Record) [Link]();
[Link](r);
}
}
catch (EOFException e) { [Link]("No more records");
}
catch (ClassNotFoundException e) {
[Link]("Unable to create object");
}
catch (IOException e) { [Link](); }
}
}
11/3/2025 Streams Page 43
RandomAccessFile class
is an independent class inherited from the Object class
Support reading and writing data to a file randomly
Record size must be fixed
11/3/2025 Streams Page 44
Example
import [Link].*;
public class WriteRandomFile {
public static void main(String args[]) {
int a[] = { 2, 3, 5, 7, 11, 13 };
try {
File fout = new File(args[0]);
RandomAccessFile out = new RandomAccessFile(fout, "rw");
for (int i=0; i<[Link]; i++)
[Link](a[i]);
[Link]();
}
catch (IOException e) { [Link](); }
}
}
11/3/2025 Streams Page 45
Example…
import [Link].*;
public class ReadRandomFile {
public static void main(String args[]) {
try {
File fin = new File(args[0]);
RandomAccessFile in = new RandomAccessFile(fin, "r");
int recordNum = (int) ([Link]() / 4);
for (int i=recordNum-1; i>=0; i--) {
[Link](i*4);
[Link]([Link]()); //read 4 bytes
integer
}
}
catch (IOException e) { [Link](); }
}
}
11/3/2025 Streams Page 46
Conclusion
I/O streams
Byte streams, character streams
Sequential and random access files
11/3/2025 Streams Page 47