Chapter 4 - Files and IO
Chapter 4 - Files and IO
Advanced Programming
(CoSc 3053)
Chapter Four
Streams and File I/O
2
Objectives
In this chapter you will learn:
To create, read, write and update files.
To use class File to retrieve information about files and
directories.
The difference between text and binary files
Save data, including objects, in a file
Read data, including objects, in a file
To use a JFileChooser dialog.
3
Introduction
Data stored in variables, arrays, and objects are temporary.
To permanently store the data created in a program, you need to
save them in a file on a secondary storage device.
Computers use files for long-term retention of large amounts of
data.
We refer to data maintained in files as persistent data.
In this chapter, we discuss Java’s powerful file-processing and
stream input/output features.
4
Data Hierarchy
Bit - smallest data item in a computer
character set is the set of all the characters used to write programs
and represent data items(Digits, letters and special symbols).
Characters in Java are Unicode characters composed of two bytes.
Fields are composed of characters or bytes(E.g. Name)
Record is a group of related fields (E.g Id, name, sex, etc for
employee record)
A file is a group of related records. E.g all employee records of an
organization.
Database – group of related files.
5
6
Files and Streams
Java views each file as a sequential stream of bytes.
The term “stream” refers to ordered data that is read from or
written to a file.
File streams can be used to input and output data as either
characters or bytes.
Streams that input and output characters to files are known as
character-based streams.
Streams that input and output bytes to files are known as byte-
based streams.
7
Files and Streams (cont’d)
Files created using character-based streams are referred to as
text files.
Files that are created using byte-based streams are referred to as
binary files.
Text files can be read by text editors, while binary files are read
by a program that converts the data to a human-readable format.
8
Class File
Useful for retrieving information about files or directories from
disk.
Objects of class File do not open files or provide any file-
processing capabilities.
However, File objects are used frequently with objects of other
java.io classes to specify files or directories to manipulate.
Creating File Objects
public File( String name )
specifies the name of a file or directory to associate with
the File object.
9
Class File (cont’d)
Example
import java.io.File;
public class TestFileClass {
public static void main(String[] args) {
File file = new File(“D:/welcome.java");
System.out.println("Does it exist? "+ file.exists() );
System.out.println("The file has " + file.length() + " bytes");
System.out.println("Can it be read? " + file.canRead());
System.out.println("Can it be written? " + file.canWrite());
System.out.println("Is it a directory? " + file.isDirectory());
System.out.println("Is it a file? " + file.isFile());
System.out.println("Is it absolute? " + file.isAbsolute());
System.out.println("Is it hidden? " + file.isHidden());
System.out.println("Name of the file? " + file.getName());
System.out.println("Parent Directory? " + file.getParent());
System.out.println("Absolute path is " +
file.getAbsolutePath());
System.out.println("Last modified on " +
new java.util.Date(file.lastModified()));
}
}
10
File Input and Output
11
File Input and Output (cont’d)
Example
import java.io.*;
public class WriteData {
public static void main(String[] args) throws Exception {
File file = new File("score.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(0);
}
// Create a file
PrintWriter output = new PrintWriter(file);
//Write formatted output to the file
output.print("John");
output.println(24);
output.print("Eric");
output.println(85);
// Close the file
output.close();
}
}
12
File Input and Output (cont’d)
Reading Data Using Scanner
To read from a file, create a Scanner for a file, as follows:
Scanner input = new Scanner(new File(filename));
13
File Input and Output (cont’d)
Example 1
import java.io.File;
import java.util.Scanner;
public class ReadData {
public static void main(String[] args) throws Exception {
File file = new File("score.txt");
if (file.exists()) {
// Create a Scanner for the file
Scanner input = new Scanner(file);
while (input.hasNext()) {
String firstName = input.next();
String age = input.next();
String lastName = input.next();
int score = input.nextInt();
System.out.println(firstName + " " + mi + " " + lastName + " " + score);
}
14
File Input and Output (cont’d)
//close the file
input.close();
}
else{
System.out.println("File does not exist");
}
}
}
15
Binary I/O
16
Text I/O vs. Binary I/O
Computers do not differentiate binary files and text files.
All files are stored in binary format, and thus all files are
essentially binary files.
Encoding and decoding are automatically performed for text I/O.
17
Text I/O vs. Binary I/O (cont’d)
18
Text I/O vs. Binary I/O (cont’d)
a) Text I/O
b) Binary I/O
19
Text I/O vs. Binary I/O (cont’d)
Binary I/O is more efficient than text I/O, because binary I/O
does not require encoding and decoding.
Binary files are independent of the encoding scheme on the host
machine and thus are portable.
Java programs on any machine can read a binary file created by a
Java program.
This is why Java class files are binary files. Java class files can
run on a JVM on any machine.
20
FileInputStream/FileOutputStream
FileInputStream/FileOutputStream is for reading/writing bytes
from/to files.
A java.io.FileNotFoundException will occur if you attempt to
create a FileInputStream with a nonexistent file.
Example
import java.io.*;
public class TestFileStream {
public static void main(String[] args) throws IOException {
// Create an output stream to the file
FileOutputStream output = new FileOutputStream("temp.dat",
true); //If append is true, data are appended to the existing file.
21
FileInputStream/FileOutputStream(cont’d)
// Output values to the file
for (int i = 1; i <= 10; i++)
output.write(i);
// Close the output stream
output.close();
// Create an input stream for the file
FileInputStream input = new FileInputStream("temp.dat");
// Read values from the file
int value;
while ((value = input.read()) != -1)
System.out.print(value + " ");
}
}
22
Random-Access Files
Java provides the RandomAccessFile class to allow a file to be
read from and written to at random locations.
When creating a RandomAccessFile, you can specify one of two
modes
Mode “r” means that the stream is read-only,
and mode “rw” indicates that the stream allows both read and
write.
A random-access file consists of a sequence of bytes.
A special marker called a file pointer is positioned at one of these
bytes.
A read or write operation takes place at the location of the file
pointer.
23
Random-Access Files (cont’d)
Example:
If you read an int value using readInt(), the JVM reads 4 bytes from
the file pointer, and now the file pointer is 4 bytes ahead of the
previous location, as shown in Figure.
24
Random-Access Files(cont’d)
Example
import java.io.*;
public class TestRandomAccessFile {
public static void main(String[] args) throws IOException {
// Create a random access file
RandomAccessFile inout = new RandomAccessFile("inout.dat", "rw");
// Write new integers to the file
for (int i = 0; i < 200; i++)
inout.writeInt(i);
// Display the current length of the file
System.out.println("Current file length is " + inout.length());
// Retrieve the first number
inout.seek(0); // Move the file pointer to the beginning
System.out.println("The first number is " + inout.readInt());
25
Random-Access Files(cont’d)
// Retrieve the second number
inout.seek(1*4); // Move the file pointer to the second number
System.out.println("The second number is " + inout.readInt());
// Retrieve the tenth number
inout.seek(9*4); // Move the file pointer to the tenth number
System.out.println("The tenth number is " + inout.readInt());
// Modify the eleventh number
inout.writeInt(555);
// Append a new number
inout.seek(inout.length()); // Move the file pointer to the end
inout.writeInt(999);
// Display the new length
System.out.println("The new length is " + inout.length());
// Retrieve the new eleventh number
inout.seek(10 * 4); // Move the file pointer to the eleventh number
System.out.println("The eleventh number is " + inout.readInt());
inout.close();
}
}
26