0% found this document useful (0 votes)
2 views22 pages

Lecture-25-Introduction to File IO

The document provides an introduction to File Input/Output (I/O) in Java, explaining the importance of saving data permanently and how to handle files using the java.io package. It details the types of streams (byte and character) for reading and writing data, along with key classes for file operations such as PrintWriter and Scanner. Additionally, it covers file handling techniques, including the use of absolute and relative file names, and the try-with-resources statement for automatic resource management.

Uploaded by

awaismumtaz1406
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)
2 views22 pages

Lecture-25-Introduction to File IO

The document provides an introduction to File Input/Output (I/O) in Java, explaining the importance of saving data permanently and how to handle files using the java.io package. It details the types of streams (byte and character) for reading and writing data, along with key classes for file operations such as PrintWriter and Scanner. Additionally, it covers file handling techniques, including the use of absolute and relative file names, and the try-with-resources statement for automatic resource management.

Uploaded by

awaismumtaz1406
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/ 22

Lecture – 25

Introduction to File I/O


Introduction
• Data stored in the program are temporary;
– It get lost when the program terminates
• To permanently store the data created in a program,
– Need to save them in a file on a disk or other permanent storage
device
• The file can then be transported and read later by other
programs
Why Use File I/O in OOP?
• Save object data (state) to external files.

• Load data (e.g., configuration, records) at runtime.

• Enables creation of reusable and extensible components.

4-3
Introduction
• File Handling
– Way to handle the files stored on the hard disk
– So that we can, read and write the data in file
– File handling is a way to interact with external files—to either save
data or retrieve it.
• Java provides java.io package
– Contain all class that help in performing input and output operations
on files
• The main purpose of file handling is to:

• Read data from a file (input operation)

• Write data to a file (output operation)

• Example: Reading a list of books from books.txt or writing


exam scores to grades.csv.

4-5
Java provides java.io package
• Java provides java.io package
"Contain all class that help in performing input and output operations on files"
 java.io is a built-in Java package that provides classes for:
• File creation
• File reading and writing
• Stream-based input/output (both byte and character streams)
 Common classes include:
• File, FileReader, FileWriter
• BufferedReader, BufferedWriter
• FileInputStream, FileOutputStream
• ObjectInputStream, ObjectOutputStream (for saving objects)
(java.io) to provide reusable, ready-to-use classes for performing file operations,
making it easier for developers to store and retrieve data persistently.
4-6
• Stream
Java Streams – A stream is a sequence of data.
– In Java, a stream is composed of bytes
called a stream

In java.io package all classes are divided into two Stream represent Source( which generate
type of streams the data in form of streams) and
1- Character Stream(for reading/writing text Destination (which consume or read data
(characters). available on stream)
2- Byte Stream(for reading/writing binary data
(bytes).
What is a Byte Stream?
• It deals with binary data — the raw sequence of 0's and 1's.
• This kind of data could be audio, video, or text files.
• It reads or writes data one byte at a time (1 byte = 8 bits).
Why Use Byte Streams?
• Useful for handling non-text data like images, videos, or any file
with binary content.

4-8
Byte Stream
(100111010111101011101)
• Raw sequence of 0's and 1’s to represent
data BufferedInputStream
• The data belong to either audio, video or BufferedoutputStream
text. ByteArrayInputStream
• Just read/write data in form of 8bits(byte ByteArrayOutputStream
by byte) DataInputStream
• Java classes that handle Byte Stream and DataOutputStream
FileInputStream
They come from three main sources:
FileOutputStream
– java.io.InputStream PrintStream
– java.io.OutputStream
– java.io.RandomAccessFile
Examples of Byte Stream Classes
• BufferedInputStream / BufferedOutputStream: For fast reading/writing
using a buffer.
• ByteArrayInputStream / ByteArrayOutputStream: Works with byte
arrays.
• DataInputStream / DataOutputStream: Allows reading/writing Java
primitive data types (like int, double).
• FileInputStream / FileOutputStream: For reading/writing raw bytes
from/to files.
• PrintStream: Used to print data in a byte stream format (often used with
System.out).

4-10
What is a Character Stream?
• A Character Stream is used to read and write text data
(characters) instead of binary data (like in Byte Stream).
• It is based on Byte Stream but works with 16 bits at a time
(because Java characters are 16-bit, using Unicode).
• Character Stream works only with character data (not binary
files like images or videos).
• It uses Unicode encoding, which can represent characters from
many languages.
• It is ideal for reading/writing text files.
4-11
Character Stream
(11110110 11010101 101010101)
• Character Stream is based on Byte
stream, and bunch of 16 bits are picked BufferedReader
as character BufferedWriter
CharArrayReader
• Data must be characters CharArrayWriter
• Characters are encoded using a character FileReader
encoding scheme such as Unicode FileWriter
InputStreamReader
• The classes that handle Character Stream OutputStreamWriter
and which are descendent of PrintWriter
– java.io.Reader StringReader
– java.io.Writer class StringWriter
Main Java Classes for Character Stream:
• BufferedReader / BufferedWriter: Fast reading/writing using a buffer.
• CharArrayReader / CharArrayWriter: Works with character arrays.
• FileReader / FileWriter: Reads/writes from text files.
• InputStreamReader / OutputStreamWriter: Converts byte streams into
character streams and vice versa.
• PrintWriter: Prints formatted text.
• StringReader / StringWriter: Works with strings as input/output.

4-13
File Class
The File class is used to work with files and folders (directories).It helps you check properties of a
file or directory (like if it exists or not).It also allows you to rename or delete files/folders.

Two Types of File Names:


• Absolute file name(full name)
– Contains a file name with its complete path and drive letter
– Example “c:\book\Welcome.java”
• Relative file name (In relation to current directory
– The complete directory path for a relative file name is omitted
– Example: Welcome.java is a relative file name. If the current working directory is
c:\book
• Do not use absolute file names in your program
File Input and Output
Use the Scanner class for reading text data from a file and the PrintWriter class for writing text data to a file.

• A File object encapsulates the properties of a file or a path


– Does not contain the methods for writing/reading data to/from a file
– Referred to as data input and output, or I/O
• To perform I/O
– Create objects using appropriate Java I/O classes
Writing Data Using PrintWriter
• The java.io.PrintWriter class can be used to create a file and
write data to a text file
• Can use print, println, and printf methods on the PrintWriter
object to write data to a file
Writing Data Using PrintWriter
java.io.PrintWriter
+PrintWriter(filename: String) Creates a PrintWriter for the specified file.
+print(s: String): void Writes a string.
+print(c: char): void Writes a character.
+print(cArray: char[]): void Writes an array of character.
+print(i: int): void Writes an int value.
+print(l: long): void Writes a long value.
+print(f: float): void Writes a float value.
+print(d: double): void Writes a double value.
+print(b: boolean): void Writes a boolean value.
Also contains the overloaded A println method acts like a print method; additionally it
println methods. prints a line separator. The line separator string is defined
Also contains the overloaded by the system. It is \r\n on Windows and \n on Unix.
printf methods.
Try-with-resources
Programmers often forget to close the file. JDK 7 and above provides the
followings new try-with-resources syntax that automatically closes the files.
try (declare and create resources) {
Use the resource to process the file;
}

try( PrintWriter output = new PrintWriter(file); )


{
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
}
Reading Data Using Scanner
• To read from keyboard
– Scanner input = new Scanner(System.in);
• To read from file
– Scanner input = new Scanner(new File(fileName));
Reading Data Using Scanner
java.util.Scanner
+Scanner(source: File) Creates a Scanner object to read data from the specified file.
+Scanner(source: String) Creates a Scanner object to read data from the specified string.
+close() Closes this scanner.
+hasNext(): boolean Returns true if this scanner has another token in its input.
+next(): String Returns next token as a string.
+nextByte(): byte Returns next token as a byte.
+nextShort(): short Returns next token as a short.
+nextInt(): int Returns next token as an int.
+nextLong(): long Returns next token as a long.
+nextFloat(): float Returns next token as a float.
+nextDouble(): double Returns next token as a double.
+useDelimiter(pattern: String): Sets this scanner’s delimiting pattern.
Scanner
public static void main(String[] args){
try{
File file = new File("File/name1.txt");
Scanner input = new Scanner(file);

while(input.hasNext()){
String fName = input.next();
String mName = input.next();
String lName = input.next();
int age = input.nextInt();
System.out.println(fName+" "+mName+" "+lName+" "+age);
}
input.close();
}
catch(IOException e){

You might also like