0% found this document useful (0 votes)
13 views26 pages

Lecture10 - ICT102 - T222 For Lecture Class

lect

Uploaded by

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

Lecture10 - ICT102 - T222 For Lecture Class

lect

Uploaded by

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

ICT102

Introduction to Programming
Lecture 10 – File IO and Streams

CRICOS 03171A
Focus for this week

01 File Input and Output (IO)

02 Binary Files, Streams and Random Access File


4-3

File Input and Output


• WHY?
– Reentering data all the time could get tedious for the
user.
– Move data from one computer to another
• Files can be input files or output files.
• Files:
– Files have to be opened.
– Data is then written to or read from the file.
– The file must be closed prior to program termination.
4-4

Different types of files and Modes


• In general, there are two types of files:
– Text
– Binary

• Different modes
– Read
– Write
– Read/Write

• File Access Modes


– Sequential
– Random
4-5

Text File – Writing to a File


• To open a file for text output you create an instance (object) of the
PrintWriter class.

PrintWriter outputFile = new PrintWriter("StudentData.txt");

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

The PrintWriter Class


• The PrintWriter class allows you to write data to a file using the print
and println methods, as you have been using to display data on the
screen.
• Just as with the System.out object, the println method of the
PrintWriter class will place a newline character after the written data.
• The print method writes data without writing the newline character.
4-7

The PrintWriter Class


Open the file.

PrintWriter outputFile = new PrintWriter("Names.txt");


outputFile.println("Chris");
outputFile.println("Kathryn");
outputFile.println("Jean");
outputFile.close();

Close the file.

Write data to the file.


4-8

The PrintWriter Class


• To use the PrintWriter class, put the following import statement at the top of the
source file:

import java.io.*;

• See example: FileWriteDemo.java


4-9

Text File – Appending Text to a File


• To avoid erasing a file that already exists, create a FileWriter object in this manner:

FileWriter fw =
new FileWriter("names.txt", true);

• Then, create a PrintWriter object in this manner:


PrintWriter fw = new PrintWriter(fw);
4-10

Specifying a File Location


• On a Windows computer, paths contain backslash (\) characters.

• 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

Text File – Reading Data From a File


• You use the File class and the Scanner class to read data from a file:

Pass the name of the file as an


argument to the File class
constructor.

File myFile = new File("Customers.txt");


Scanner inputFile = new Scanner(myFile);

Pass the File object as an


argument to the Scanner
class constructor.
4-12

Text File – Reading Data From a File


Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);

• The lines above:


– Creates an instance of the Scanner class to read from the
keyboard
– Prompt the user for a filename
– Get the filename from the user
– Create an instance of the File class to represent the file
– Create an instance of the Scanner class that reads from the file
4-13

Text File – Reading Data From a File


• Once an instance of Scanner is created, data can be
read using the same methods that you have used to read
keyboard input (nextLine, nextInt, nextDouble,
etc).

// Open the file.


File file = new File("Names.txt");
Scanner inputFile = new Scanner(file);
// Read a line from the file.
String str = inputFile.nextLine();
// Close the file.
inputFile.close();
4-14

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.

public static void main(String[] args) throws IOException {

• We will be discussing Exceptions in detail next week.


4-15

Detecting The End of a File


• The Scanner class’s hasNext() method will return true if another item can be read from
the file.
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Read until the end of the file.
while (inputFile.hasNext())
{
String str = inputFile.nextLine();
System.out.println(str);
}
inputFile.close();// close the file when done.
4-16

Detecting the End of a File


• import java.util.Scanner; // Needed for the Scanner class

• import java.io.*; // Needed for the File class

• /** This program reads data from a file.*/

• public class FileReadDemo {

• public static void main(String[] args) throws IOException {

Scanner keyboard = new Scanner(System.in); // Create a Scanner object for keyboard input.

• System.out.print("Enter the filename: "); // Get the filename.

• String filename = keyboard.nextLine();

• File file = new File(filename); // Open the file.

• Scanner inputFile = new Scanner(file);

• while (inputFile.hasNext()) { // Read lines from the file until no more are left.

• String friendName = inputFile.nextLine(); // Read the next name.

• System.out.println(friendName); // Display the last name read. }

• inputFile.close(); // Close the file.

• }. }
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 – Writing Data


• A DataOutputStream object is wrapped around a
FileOutputStream object to write data to a binary file.

FileOutputStream fstream = new


FileOutputStream("MyInfo.dat");
DataOutputStream outputFile = new
DataOutputStream(fstream);

• If the file that you are opening with the


FileOutputStream object already exists, it will be
erased and an empty file by the same name will be
created.
11-20

Binary Files
• These statements can combined into one.

DataOutputStream outputFile = new


DataOutputStream(new
FileOutputStream("MyInfo.dat"));

• Once the DataOutputStream object has been


created, you can use it to write binary data to the
file.
11-21

Binary Files – Reading Data


• To open a binary file for input, you wrap a
DataInputStream object around a FileInputStream
object.
FileInputStream fstream = new
FileInputStream("MyInfo.dat");
DataInputStream inputFile = new
DataInputStream(fstream);

• These two statements can be combined into one.


DataInputStream inputFile = new DataInputStream(new
FileInputStream("MyInfo.dat"));
4-22

Write to a Binary File


• import java.io.*;

• /**. This program opens a binary file and writes the contents of an int array to the file.*/

• public class WriteBinaryFile

• {

• public static void main(String[] args) throws IOException

int[] numbers = { 2, 4, 6, 8, 10, 12, 14 }; // An array to write to the file

FileOutputStream fstream = new FileOutputStream("Numbers.dat"); // Create the binary output objects.

DataOutputStream outputFile = new DataOutputStream(fstream);

• System.out.println("Writing the numbers 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.");

• outputFile.close(); // Close the file.

• }. }
4-23

Read from a Binary File


• import java.io.*;

/** This program opens a binary file, reads and displays the contents.*/

• public class ReadBinaryFile {

• public static void main(String[] args) throws IOException. {

int number; // A number read from the file

boolean endOfFile = false; // EOF flag

• FileInputStream fstream = new FileInputStream("Numbers.dat"); // Create the binary file input objects.

DataInputStream inputFile = new DataInputStream(fstream);

• System.out.println("Reading numbers from the file:");

while (!endOfFile) {. // Read the contents of the file.

try {

number = inputFile.readInt()

System.out.print(number + " ");

} catch (EOFException e)

{ endOfFile = true; } } System.out.println("\nDone."); inputFile.close(); // Close the file. } }


11-24

Binary Files - Appending Data


• The FileOutputStream constructor takes an
optional second argument which must be a
boolean value.
• If the argument is true, the file will not be erased
if it exists; new data will be written to the end of
the file.
• If the argument is false, the file will be erased if
it already exists.
FileOutputStream fstream = new
FileOutputStream("MyInfo.dat", true);
DataOutputStream outputFile = new
DataOutputStream(fstream);
11-25

Sequential Access Files


• Text files and the binary files previously shown use
sequential file access.
• With sequential access:
– The first-time data is read from the file, the data will be read from
its beginning.
– As the reading continues, the file’s read position advances
sequentially through the file’s contents.

• Sequential file access is useful in many circumstances.


• If the file is very large, locating data buried deep inside it
can take a long time e.g. Search.
11-26

Random Access Files


• Java allows a program to perform random file access.
• In random file access, a program may immediately jump to
any location in the file.
• To create and work with random access files in Java, you
use the RandomAccessFile class.

You might also like