0% found this document useful (0 votes)
16 views33 pages

Chapter 3 - Files and IO-1

Chapter Three covers file and stream I/O in Java, teaching how to create, read, write, and update files, as well as the differences between text and binary files. It introduces the File class for retrieving file information and explains the use of PrintWriter and Scanner for file output and input, respectively. Additionally, it discusses serialization for object storage and the RandomAccessFile class for accessing files at random locations.

Uploaded by

mamomohi13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views33 pages

Chapter 3 - Files and IO-1

Chapter Three covers file and stream I/O in Java, teaching how to create, read, write, and update files, as well as the differences between text and binary files. It introduces the File class for retrieving file information and explains the use of PrintWriter and Scanner for file output and input, respectively. Additionally, it discusses serialization for object storage and the RandomAccessFile class for accessing files at random locations.

Uploaded by

mamomohi13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 33

Chapter Three

Streams and File I/O

1
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

2
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.

3
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)
 A field is a group of characters or bytes that conveys
meaning.
 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.
4
Data Hierarchy…
 To facilitate the retrieval of specific records from a
file, at least one field in each record is chosen as a
record key.
 A record key identifies a record as belonging to a
particular person or entity and is unique to each
record.
 There are many ways to organize records in a file.
 The most common is called a sequential file, in which
records are stored in order by the record-key field.
 A group of related files is often called a database.
 A collection of programs designed to create and
manage databases is called a database
management system (DBMS).
5
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.

6
Files and Streams …
 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.

Java’s view of a file of n bytes.

7
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.

8
9
Class File (cont’d)
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
 A File object encapsulates the properties of a file or a path
but does not contain the methods for creating a file or for
reading/writing data from/to a file.
 In order to perform I/O, you need to create objects using
appropriate Java I/O classes.
 The objects contain the methods for reading/writing data
from/to a file.
 Writing Data Using PrintWriter
 The java.io.PrintWriter class can be used to create a file
and write data to a text file.
 First, you have to create a PrintWriter object for a text file
as follows:
 PrintWriter output = new PrintWriter(filename);
 Then, you can invoke the print, println, and printf methods
on the PrintWriter object to write data to a file.

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 T Smith ");
output.println(90);
output.print("Eric K Jones ");
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 mi = 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
File Input and Output (cont’d)
 Example 2
import java.util.Scanner;
import javax.swing.JFileChooser;
public class FileGUI {
public static void main(String[] args) throws Exception {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
// Get the selected file
java.io.File file = fileChooser.getSelectedFile();
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read text from the file
while (input.hasNext()) {
System.out.println(input.nextLine());
}
// Close the file
input.close();
}
}
}

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.
 The JVM converts a Unicode to a file-specific encoding
when writing a character and converts a file-specific
encoding to a Unicode when reading a character.
 use text input to read a file created by a text editor or a
text output program, and use binary input to read a file
created by a Java binary output program.

17
Text I/O vs. Binary I/O (cont’d)

 The program receives data through an input


object and sends data through an output object.

18
Text I/O vs. Binary I/O (cont’d)

a) Text I/O

b) Binary I/O

Text I/O requires encoding and decoding,


whereas binary I/O does not.

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
Binary I/O Classes
 The following figure shows the hierichical
relashinship of binary I/O class.
 InputStream is the root for binary input
classes, and OutputStream is the root for
binary output classes.

21
FileInputStream/
FileOutputStream
 FileInputStream/FileOutputStream is for
reading/writing bytes from/to files.
 To construct a FileInputStream
 FileInputStream(file: File) - Creates a FileInputStream
from a File object.
 FileInputStream(filename: String)-Creates a
FileInputStream from a file name.
 A java.io.FileNotFoundException will occur if you
attempt to create a FileInputStream with a
nonexistent file.

22
 To construct a FileOutputStream, use the constructors
 FileOutputStream(file: File)
 +FileOutputStream(filename: String)
 +FileOutputStream(file: File, append: boolean)
 +FileOutputStream(filename: String, append: boolean)
 Creates a FileOutputStream from a File object.
 Creates a FileOutputStream from a file name.
 If append is true, data are appended to the existing file.
 If append is true, data are appended to the existing file.

23
 Almost all the methods in the I/O classes throw java.io.IOException. Therefore you
 have to declare java.io.IOException to throw in the method or place the code
in a trycatch
 block,
 public static void main(String[] args)
 throws IOException {
 // Perform I/O operations
 } as shown below:
 public static void main(String[] args) {
 try {
 // Perform I/O operations
 }
 catch (IOException ex) {
 ex.printStackTrace();
 }
 }

24
FileInputStream/FileOutputStream(cont’d)
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.

// 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 + " ");

// Close the input stream


input.close();

}
}
25
DataInputStream/DataOutputStream
 File stream can be used only for reading bytes and
characters.
 Using a filter class enables you to read integers, doubles,
and strings instead of bytes and characters.
 To process primitive numeric types, use
DataInputStream and DataOutputStream.
 DataInputStream reads bytes from the stream and
converts them into appropriate primitive type values or
strings.
 DataOutputStream converts primitive type values or
strings into bytes and outputs the bytes to the stream.
 Example: TestDataStream.java

26
The Serializable Interface
 Serialization is the process of transforming an object into a
stream of bytes.
 Deserialization is the reverse prorcess.
 Objects of classes that implement the java.io.Seralizable
interface can be serializaed and deserialized.
 Serialization allows objects to be easily saved to files or
sent to remote hosts over a network.
 ObjectInputStream/ObjectOutputStream enables you to
perform I/O for objects.

27
Serializable(cont’d)
 Example
import java.io.*;
import java.io.Serializable;
public class TestObjectIOStream implements Serializable {
public static void main(String[] args) throws ClassNotFoundException,
IOException {
// Create an output stream for file object.dat
ObjectOutputStream output =
new ObjectOutputStream(new FileOutputStream("object.dat"));
// Write a string, double value, and object to the file

output.writeUTF("John");
output.writeDouble(85.5);
output.writeObject(new java.util.Date());
// Close output stream
output.close();

28
Serializable(cont’d)
// Create an input stream for file object.dat
ObjectInputStream input =
new ObjectInputStream(new FileInputStream("object.dat"));

// Write a string, double value, and object to the file

String name = input.readUTF();


double score = input.readDouble();
java.util.Date date = (java.util.Date)(input.readObject());
System.out.println(name + " " + score + " " + date);

// Close input stream


input.close();

}
}

29
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.
30
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.

31
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());

32
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();
}
}

33

You might also like