Lecture_09_FileIO
Lecture_09_FileIO
Input/Output
CSIT213 Java Programming
Overview
• Files and streams
• Object serialization
2
Files and Streams
• Java views each file as a sequential stream of bytes.
• Every operating system provides a mechanism to determine the end of a
file, such as an end-of-file marker or a count of the total bytes in the file
that is recorded in a system-maintained administrative data structure.
• A Java program simply receives an indication from the operating
system when it reaches the end of the stream.
3
Files and Streams
• File streams can be used to input and output data as bytes or characters.
- Byte-based streams output and input data in its binary format—a char is
two bytes, an int is four bytes, a double is eight bytes,...
- Character-based streams output and input data as a sequence of
characters in which every character is two bytes—the number of bytes
for a given value depends on the number of characters in that value.
• Files created using byte-based streams are referred to as binary files.
• Files created using character-based streams are referred to as text files. Text
files can be read by text editors.
• Binary files are read by programs that understand the specific content of
the file and the ordering of that content.
- Reading binary files is generally much faster.
4
Files and Streams
• A Java program opens a file by creating an object and associating a stream
of bytes or characters with it.
• Character-based input and output can be performed with classes Scanner and
Formatter.
- Class Scanner is used extensively to input data from the keyboard. This class
can also read data from a file.
- Class Formatter enables formatted data to be output to any text-based stream
like method System.out.printf.
7
Using NIO Classes and Interfaces
• Files class: provides static methods for common file and directory
manipulations. Such as copying files, creating and deleting files and
directories, getting information about files and directories, reading the
contents of files, getting objects that allow you to manipulate the
contents of files and directories, and more.
8
Using NIO Classes and Interfaces
• A file or directory’s path specifies its location on a disk. The path includes
some or all the directories leading to the file or directory.
• An absolute path contains all directories, starting with the root directory
that leads to a specific file or directory.
• Every file or directory on a particular disk drive has the same root directory
in its path.
9
Using NIO Classes and Interfaces
• An overloaded version of the Files static method uses a URI object to
locate the file or directory.
• A Uniform Resource Identifier (URI) is a more general form of the Uniform
Resource Locators (URLs) that are used to locate websites.
- On Windows platforms, the URI
file://C:/data.txt
identifies the file data.txt stored in the root directory of the C: drive.
- On UNIX/Linux platforms, the URI
file:/home/student/data.txt
identifies the file data.txt stored in the home directory of the user student.
10
Using NIO Classes and Interfaces
• A separator character is used to separate directories and files in a path.
– On a Windows computer, the separator character is a backslash (\).
– On a Linux or Mac OS X system, it’s a forward slash (/).
11
testFile.java
12
Example - a file/directory information
if(Files.isDirectory(path)) {
System.out.println("Directory contains:");
DirectoryStream<Path> ds = Files.newDirectoryStream(path);
for(Path p : ds)
System.out.println(p);
}
else {
System.out.printf("%s is a file.\n", path);
System.out.printf("Last modified: %s\n", Files.getLastModifiedTime(path));
System.out.printf("Size: %s\n", Files.size(path));
System.out.printf("Absolute path: %s\n", path.toAbsolutePath());
}
13
Read data from a sequential-access text file
• Sequential-access files store records in order.
- If a path is not specified, the JVM assumes that the file is in the
directory from which the program was executed.
14
sampleFile1.txt
15
Example - class Department
class Department {
private int number;
private String name;
private int manager;
private double budget;
private String startDate;
public Department(int num, String name, int mnum, double budget, String sDate) {
number = num;
this.name = name;
manager = mnum;
this.budget = budget;
startDate = sDate;
}
public String toString() {
return String.format("%d, %s, %d, %.2f, %s", number, name, manager, budget,
startDate);
}
}
16
testFile.java
if(!Files.isDirectory(path)) {
Scanner fin = new Scanner(path);
fin.useDelimiter(", |\r\n|\t|\n");
17
Example - read department records
while(fin.hasNext()) {
int number = fin.nextInt();
String dname = fin.next();
int manager = fin.nextInt();
double budget = fin.nextDouble();
String sDate = fin.next();
18
Creating a sequential - access text file
• Formatter outputs formatted Strings to the specified stream.
• The constructor of Formatter with one String argument receives the name
of the file, including its path.
- If a path is not specified, the JVM assumes that the file is in the directory
from which the program was executed.
19
Example - save department records
public void writeFile() {
System.out.print("Input an output filename: ");
String name = keyboardIn.nextLine();
try {
Formatter fout = new Formatter(name);
for(Department d:departments) {
fout.format("%s\n", d);
}
fout.close();
}
catch (IOException err) {
System.out.println("IO exception error");
}
}
20
Object Serialization
• To read an entire object from or write an entire object to a file, Java provides
object serialization.
• After a serialized object has been written into a file, it can be read from the
file and deserialized to recreate the object in memory.
21
Object Serialization
22
Object Serialization
• ObjectOutput interface method writeObject takes an Object as an
argument and writes its information to an OutputStream.
23
Object Serialization
• Objects of classes that implement interface Serializable can be serialized
and deserialized with ObjectOutputStreams and ObjectInputStreams.
24
Object Serialization
• In a class that implements Serializable, every variable must be
Serializable.
• Anyone that is not must be declared transient, it will be ignored during the
serialization process.
25
Object input serialization
26
testBFile.java
Example - Serializable
class Student implements Serializable {
private int number;
private String name;
private String dob;
private String email;
private String address;
private String phone;
private String degree;
…
public String toString() {
return String.format("%d, %s, %s, %s, %s, %s, %s", number, name, dob,
email, address, phone, degree);
}
}
27
Example - output data to a binary file
public void writeBFile() {
System.out.print("Input an output filename: ");
String name = keyboardIn.nextLine();
try {
ObjectOutputStream fout = new
ObjectOutputStream(Files.newOutputStream(Paths.get(name)));
for(Student s:students) {
fout.writeObject(s);
}
fout.close();
}
catch (IOException err) {
System.out.println("IO exception error. " + err);
}
}
28
Example - read data from a binary file
public void readBFile() {
System.out.print("Binary filename: ");
String name = keyboardIn.nextLine();
Path path = Paths.get(name);
ObjectInputStream fin = null;
try {
if(Files.exists(path)) {
if(!Files.isDirectory(path)) {
fin = new ObjectInputStream(Files.newInputStream(path));
students.add(s);
}
}
29
Example – read data from a binary file
else
System.out.printf("File %s is a directory.\n", path);
}
else
System.out.printf("File %s does not exist.\n", path);
}
catch (EOFException err) {
System.out.println("No more records.");
try {
if(fin != null)
fin.close();
}
catch(IOException e) {
System.out.printf("Close the file %s failed. Error=%s\n", path, e);
}
}
30
Example – read data from a binary file
catch (ClassNotFoundException err) {
System.out.println("Invalid object type. " + err);
}
catch (IOException err) {
System.out.println("IO exception error. " + err);
}
}
31