Streams and File I/O: Dr. M. Ishtiaq
Streams and File I/O: Dr. M. Ishtiaq
Streams and File I/O: Dr. M. Ishtiaq
Dr. M. Ishtiaq
Objectives
• become familiar with the concept of an I/O
stream
• understand the difference between binary files
and text files
• learn how to save data in a file
• learn how to read data from a file
I/O Overview
• I/O = Input/Output
• In this context it is input to and output from programs
• Input can be from keyboard or a file
• Output can be to display (screen) or a file
• Advantages of file I/O
• permanent copy
• output from one program can be input to another
• input can be automated (rather than entered
manually)
Streams
• Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data
from a source (keyboard, file, etc.)
• it acts as a buffer between the data source and destination
• Input stream: a stream that provides input to a program
• System.in is an input stream
• Output stream: a stream that accepts output from a program
• System.out is an output stream
• A stream connects a program to an I/O object
• System.out connects a program to the screen
• System.in connects a program to the keyboard
Types of Streams
• There are 2 kinds of streams
• byte streams
• character streams
Character Streams
• Character streams create text files.
• These are files designed to be read with a text editor.
• Java automatically converts its internal unicode characters to the
local machine representation (ASCII in our case).
Byte Streams
• Byte streams create binary files.
• A binary file essentially contains the memory
image of the data. That is, it stores bits as they
are in memory.
• Binary files are faster to read and write because
no translation need take place.
• Binary files, however, cannot be read with a text
editor.
Binary Versus Text Files
• All data and programs are ultimately just zeros and ones
• each digit can have one of two values, hence binary
• bit is one binary digit
• byte is a group of eight bits
• Text files: the bits represent printable characters
• one byte per character for ASCII, the most common code
• for example, Java source files are text files
• so is any file created with a "text editor"
• Binary files: the bits represent other types of encoded information, such as
executable instructions or numeric data
• these files are easily read by the computer but not humans
• they are not "printable" files
• actually, you can print them, but they will be unintelligible
• "printable" means "easily readable by humans when printed"
Java: Text Versus Binary Files
• Text files are more readable by humans
• Binary files are more efficient
• computers read and write binary files more easily than text
• Java binary files are portable
• they can be used by Java on different machines
• Reading and writing binary files is normally done by a
program
• text files are used only to communicate with humans
Text Files vs. Binary Files
• Number: 127 (decimal)
• Text file
• Three bytes: “1”, “2”, “7”
• ASCII (decimal): 49, 50, 55
• ASCII (octal): 61, 62, 67
• ASCII (binary): 00110001, 00110010, 00110111
• Binary file:
• One byte (byte): 01111110
• Two bytes (short): 00000000 01111110
• Four bytes (int): 00000000 00000000 00000000 01111110
How to do I/O
• Opening an output file creates a new file if it does not already exist
• Opening an output file that already exists eliminates the old file and creates a new, empty one
• data in the original file is lost
Closing a File
• An output file should be closed when you are done
writing to it (and an input file should be closed when you
are done reading from it).
Two reasons:
1. To make sure it is closed if a program ends abnormally (it could get
damaged if it is left open).
2. A file opened for writing must be closed before it can be opened for
reading.
• Although Java does have a class that opens a file for both
reading and writing, it is not used in this text.
Using Path Names
• Path name—gives name of file and tells which directory the file is in
• Relative path name—gives the path starting with the directory that
the program is in
• Typical UNIX path name:
/user/smith/home.work/java/FileClassDemo.java
• Typical Windows path name:
D:\Work\Java\Programs\FileClassDemo.java
• When a backslash is used in a quoted string it must be written as two
backslashes since backslash is the escape character:
"D:\\Work\\Java\\Programs\\FileClassDemo.java"
• Java will accept path names in UNIX or Windows format, regardless of
which operating system it is actually running on.
Alternative with Scanner
• Instead of BufferedReader with
FileReader, then StringTokenizer
• Use Scanner with File:
Scanner inFile =
new Scanner(new File(“in.txt”));
• Similar to Scanner with System.in:
Scanner keyboard =
new Scanner(System.in);
Reading in int’s
Scanner inFile = new Scanner(new File(“in.txt"));
int number;
while (inFile.hasInt())
{
number = inFile.nextInt();
// …
}
Reading in lines of characters
Scanner inFile = new Scanner(new File(“in.txt"));
String line;
while (inFile.hasNextLine())
{
line = inFile.nextLine();
// …
}
File I/O using FileWritter/FileReader
Example
public class File_IO {
public Student() {
this.setData(null, 0, null, 0);
}
public void setData(String name, int age, String city, float cgpa) {
this.name = name;
this.age = age;
this.city = city;
this.cgpa = cgpa;
}
File I/O using Formatter Example – contd.
public String getName() {
return name;
}
@Override
public String toString() {
return "Student{" + "name=" + name + ", age=" + age + ", city=" + city + ", cgpa=" + cgpa + '}';
}
}
File I/O using Formatter Example – contd.
public class FileFormatter {
private Formatter output;
} catch(SecurityException secExp){
} catch(FileNotFoundException fExp){
try{
} catch(FileNotFoundException exp){
System.out.println("Error: File not found.");
}
}
fileObj.readRecord("student.txt",s);
System.out.println(s);
}
}
File I/O using Object Serialization
Note: For Object Serialization, the class should implement Serializable.
So the student class defined above will be defined as:
}
File I/O using Object Serialization - Example
public class FileOutputStream {
}
}
public static void closeFile() {
try {
if (output != null) {
output.close();
}
} catch (IOException ioException) {
System.err.println("Error closing file. Terminating.");
}
}
}
File I/O using Object Serialization – Example
contd.
public class FileInputStream {
private static ObjectInputStream input; // read data from file
}
catch (IOException ioException) {
System.err.println("Error reading from file. Terminating.");
}
}
File I/O using Object Serialization – Example
contd.
public static void closeFile() {
try {
if (input != null) {
input.close();
}
} catch (IOException ioException) {
System.err.println("Error closing file. Terminating.");
}
}
} // end of class