Lecture10 - ICT102 - T222 For Lecture Class
Lecture10 - ICT102 - T222 For Lecture Class
Introduction to Programming
Lecture 10 – File IO and Streams
CRICOS 03171A
Focus for this week
• Different modes
– Read
– Write
– Read/Write
Pass the name of the file that you Warning: if the file
wish to open as an argument to the already exists, it will be
PrintWriter constructor. erased and replaced with
a new file.
4-6
import java.io.*;
FileWriter fw =
new FileWriter("names.txt", true);
• Remember, if the backslash is used in a string literal, it is the escape character so you
must use two of them:
PrintWriter outFile =
new PrintWriter("A:\\PriceList.txt");
• Java also allows Unix style filenames using the forward slash (/) to separate directories:
PrintWriter outFile = new
PrintWriter("/home/rharrison/names.txt");
4-11
Exceptions
• File related classes can throw many different exceptions(end of File, File not found
etc).
• So, we must put a throws IOException clause in the header of the method that
instantiates any such File classes.
Scanner keyboard = new Scanner(System.in); // Create a Scanner object for keyboard input.
• while (inputFile.hasNext()) { // Read lines from the file until no more are left.
• }. }
11-17
Binary Files
• Data can be stored in a file in its raw binary format.
• A file that contains binary data is often called a binary file.
• Storing data in its binary format is more efficient than
storing it as text.
• There are some types of data that should only be stored in
its raw binary format. E.g. secure data transfer over the
network
11-18
Binary Files
• Binary files cannot be opened in a text editor such as
Notepad.
• To write data to a binary file you must create objects from
the following classes:
– FileOutputStream - allows you to open a file for writing binary
data. It provides only basic functionality for writing bytes to the file.
– DataOutputStream - allows you to write data of any primitive
type or String objects to a binary file. Cannot directly access a file.
It is used in conjunction with a FileOutputStream object that
has a connection to a file.
11-19
Binary Files
• These statements can combined into one.
• /**. This program opens a binary file and writes the contents of an int array to the file.*/
• {
for (int i = 0; i < numbers.length; i++). // Write the array elements to the file.
outputFile.writeInt(numbers[i]);
• System.out.println("Done.");
• }. }
4-23
/** This program opens a binary file, reads and displays the contents.*/
• FileInputStream fstream = new FileInputStream("Numbers.dat"); // Create the binary file input objects.
try {
number = inputFile.readInt()
} catch (EOFException e)