[go: up one dir, main page]

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

Streams and File I/O: Dr. M. Ishtiaq

The document discusses input/output (I/O) streams and file I/O in Java. It covers key concepts like streams, binary vs text files, reading and writing files, and closing files. It provides examples of reading and writing files using FileWriter/FileReader, Formatter, and object serialization. The document aims to help readers become familiar with I/O streams, understand binary vs text files, and learn how to save and read data from files in Java.

Uploaded by

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

Streams and File I/O: Dr. M. Ishtiaq

The document discusses input/output (I/O) streams and file I/O in Java. It covers key concepts like streams, binary vs text files, reading and writing files, and closing files. It provides examples of reading and writing files using FileWriter/FileReader, Formatter, and object serialization. The document aims to help readers become familiar with I/O streams, understand binary vs text files, and learn how to save and read data from files in Java.

Uploaded by

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

Streams and File I/O

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

• Open the stream


• Use the stream (read, write, or both)
• Close the stream
Overwriting a File
• Opening an output file creates an empty file

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

• Use the close method of the class FileWriter


through object

• For example, to close the file:


fileWriterObj.close();
• If a program ends normally it will close any files that are
open.
Why Bother to Close a File?
If a program automatically closes files when it ends normally, why close
them with explicit calls to close?

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 static void main(String[] args) {


fileWrite();
fileRead();
}

public static void fileWrite(){


try {
FileWriter fw = new FileWriter("D:\\sample.txt");
fw.write("Welcome to File IO in Java");
fw.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("File created successfully...");
}
Example – contd.
public static void fileRead() {
try {
FileReader fr = new FileReader("D:\\sample.txt");
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
} catch (Exception e) {
System.out.println(e);
}
finally {
fr.close();
}
System.out.println("\nFile read successfully...");
}
}
File I/O using Formatter Example
public class Student {
private String name;
private int age;
private String city;
private float cgpa;

public Student() {
this.setData(null, 0, null, 0);
}

public Student(String name, int age, String city, float cgpa) {


this.setData(name, age, city, cgpa);
}

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;
}

public int getAge() {


return age;
}

public String getCity() {


return city;
}

public float getCgpa() {


return cgpa;
}

@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;

public void openFile(String fName){


try{
output = new Formatter("D:\\"+fName);

} catch(SecurityException secExp){

System.out.println("You do not have write access to this file");


System.exit(1);

} catch(FileNotFoundException fExp){

System.out.println("Error: opening or creating file");


System.exit(1);
}
}
File I/O using Formatter Example – contd.
public void addRecord(Student s){
output.format("%s %d %s %f\n",s.getName(),s.getAge(),s.getCity(),s.getCgpa());
System.out.println("File created successfully...");
}

public void readRecord(String fName, Student s){

try{

Scanner input = new Scanner(new File("D:\\"+fName));


System.out.println("Name \t age \t city \t cgpa");
s.setData(input.next(), input.nextInt(),input.next(), input.nextFloat());
System.out.println("File read successfully");
//System.out.println(s);

} catch(FileNotFoundException exp){
System.out.println("Error: File not found.");
}
}

public void closeFile(){


output.close();
output = null;
}
}
File I/O using Formatter Example – contd.
public class File_IO {

public static void main(String[] args) {

FileFormatter fileObj = new FileFormatter();


Student s2 = new Student("Zain",20,"ISB",2.75f);
fileObj.openFile("student.txt");
fileObj.addRecord(s2);
fileObj.closeFile();

// Read data from file


Student s = new Student();

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:

public class Student implements Serializable {

// definition of class, same as above

}
File I/O using Object Serialization - Example
public class FileOutputStream {

private static ObjectOutputStream output; // outputs data to file

public static void main(String[] args) {


Student s = new Student("Zain",20,"ISB",2.75f);
openFile();
addRecords(s);
closeFile();
}
File I/O using Object Serialization – Example
contd.
// open file
public static void openFile() {
try {
output = new ObjectOutputStream(
Files.newOutputStream(Paths.get("d:\\data.txt")));

} catch (IOException ioException) {


System.err.println("Error opening file. Terminating.");
System.exit(1); // terminate the program
}
}
File I/O using Object Serialization – Example
contd.
public static void addRecords(Student record) {
try {
output.writeObject(record);
} catch (IOException ioException) {
System.err.println("Error writing to file. Terminating.");

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

public static void main(String[] args) {


Student s = new Student();
openFile();
readRecords(s);
closeFile();
}
File I/O using Object Serialization – Example
contd.
// open file
public static void openFile() {
try {
input = new ObjectInputStream(
Files.newInputStream(Paths.get("d:\\data.txt")));

} catch (IOException ioException) {


System.err.println("Error opening file. Terminating.");
System.exit(1); // terminate the program
}
}
File I/O using Object Serialization – Example
contd.
public static void readRecords(Student record) {
try {
record = (Student) input.readObject();
System.out.println(record);
}
catch (ClassNotFoundException classNotFoundException) {
System.err.println("Invalid object type. Terminating.");

}
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

You might also like