0% found this document useful (0 votes)
1 views12 pages

Java Module-4 Files

The document provides a comprehensive overview of file handling in Java, detailing the use of various classes for input/output operations, including byte and character streams. It explains the concept of streams, methods for reading and writing data, and the use of the File class for managing files. Additionally, it covers exceptions, random access files, and interactive I/O, along with examples of code for practical implementation.
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)
1 views12 pages

Java Module-4 Files

The document provides a comprehensive overview of file handling in Java, detailing the use of various classes for input/output operations, including byte and character streams. It explains the concept of streams, methods for reading and writing data, and the use of the File class for managing files. Additionally, it covers exceptions, random access files, and interactive I/O, along with examples of code for practical implementation.
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

Managing Input/Output Files in Java

File handling in Java allows programs to store data permanently in files and retrieve them whenever
required. Java provides multiple classes in the [Link] and [Link] packages to support file creation,
reading, writing, and manipulation.

A file is collection of related records placed area on the disk. A record is composed of several fields.
Field is a group of characters. Storing and managing data using file is known as file processing which
includes tasks such as creating files, updating files and manipulation of data. Reading and writing of
data in a file can be done at the level of bytes or characters or fields depending on the requirement of
application.

Concept of Streams

A stream represents a continuous flow of data between a program and an external source/destination. It
represents a sequence of data that can be read from a source or written to a destination. Streams allow
Java programs to perform input and output (I/O) operations in a uniform and efficient manner.

There are two basic types of streams

1. Input Stream

2. Output stream

Input Stream:

InputStream is an abstract class representing the source of data.


It is used to read binary data (bytes) from files, networks, pipes, or memory. It reads the data from the
source file and sends it to the program.

Java
1100110011
Application

fin

[Link]
Output Stream:
OutputStream is an abstract class representing the destination of data.
It is used to write binary data (bytes) to files, networks, pipes, or memory. It takes data from the
program and sends it to the destination file.

Java 1100110011
Application

fout

[Link]
Stream classes
The [Link] package contains a large number of stream classes that provide capabilities for processing
all types of data.
The classes may be categorized into two groups based on the data type on which they operate.
1. Byte stream classes that provides support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operation on characters.
These groups may further be classified based on their functions. Byte stream and character stream
classes contain specialized classes to deal with input and output operations independently on various
type of devices. We can also cross-group the streams based on the type of source or destination they
from or write to.

1) Byte stream classes


• Byte stream classes have been designed to provide functional features for creating and manipulating
streams and files reading and writing bytes.
• Since the steams are unidirectional, they can transmit bytes in only one direction and, therefore, •
Java provides two kinds of byte stream classes:
1) input stream classes
2) output stream classes.
1) Input Stream Classes :
Input stream classes that are used to read 8-bit bytes include super class known as InputStream and a
number of subclasses for supporting various input-related functions. Figure shows class hierarchy of
input stream.
The InputStream class defines method for performing input functions such as
• Reading bytes
• Closing streams
• Marking position in streams
• Skipping ahead in a stream
• Finding the number of bytes in a stream
Summary of InputStream Methods :

Method Description
1 read() Reads a byte from the input stream
2 read(byte b[]) Reads an array of bytes into b
3 available() Gives number of bytes available in the input
4 skip(n) Skips over n bytes from the input stream
5 reset() Goes back to the beginning of the stream
6 close() Closes the input stream.

OutputStream

OutputStream is an abstract class in the [Link] package used for writing byte data (8-bit) to a
destination such as:

• File
• Network socket
• Memory buffer
• Pipe
• Other I/O devices

All byte output stream classes are subclasses of OutputStream.

The OutputStream includes methods that are designed to perform the following task:

• Writing bytes
• Closing stream
• Flushing stream
Summary of output stream methods

Method Description
1 write() Writes a byte to the output stream
2 write(byte b[]) Writes all bytes in the array b to the output stream
3 write(byte b[],int n,int m) Writes m bytes from array b starting from nth byte
4 close() Close the output stream
5 flush() writers to forcefully send any buffered data to the
destination

2. Character Stream classes


Character streams are used to read and write 16-bit Unicode characters. They are designed
specifically for text data (letters, numbers, symbols).

Character streams belong to the [Link] package.

there are two kinds of character stream classes, reader classes and writer stream classes.

1. Reader stream class


Reader stream classes are designed to read character from the files. Reader class is the base class
for all other classes.
These classes are functionally very similar to the input stream classes, except input stream use
bytes as their fundamental unit of information, while reader stream use characters.

Class Description
Reader Abstract base class for reading characters
FileReader Reads characters from a text file
BufferedReader Efficient reading using buffer, supports readLine()
InputStreamReader Converts byte stream → character stream
CharArrayReader Reads characters from a char array
StringReader Reads characters from a String
PushbackReader Allows pushing back characters to the stream

2. Writer stream classes

Like output stream classes, the writer stream classes are designed to perform all output operations on
files. Only difference is that while output stream classes are designed to write bytes, the writer stream
classes are designed to write characters.
The Writer class is an abstract class which acts as a base class for all other writer stream classes.

Class Description
Writer Abstract base class for writing characters
FileWriter Writes characters to a text file
BufferedWriter Uses buffer to speed writing
OutputStreamWriter Converts character stream → byte stream
CharArrayWriter Writes to char array
StringWriter Writes characters to a String buffer
PrintWriter Provides print(), println()

Using the file class

The [Link] package includes a class known as the File class that provides support for creating files
and directories. The class includes several constructors for instantiating the File objects.

File class provides methods for operations like:

• Creating a file
• Opening a file
• Closing a file
• Deleting a file
• Getting the name of a file
• Getting the size of a file
• Checking the existence of a file
• Renaming a file
• Checking whether the file is writable
• Checking whether the file is readable

Input/output Exceptions
When creating files and performing I/O operations on them, the system may generate I/O related
exceptions. The basic I/O related exception

n classes and their functions:

I/O exception class Function


1 EOFException Signals that an end of file or end of stream
has been reached unexpectedly during input
2 FileNotFoundException Informs that a file could not be found
3 InteruuptedIOException Warns that an I/O operations has been
interrupted
4 IOException Signals that an I/O exception of some sort
has occurred

Creation of Files
If we want to create and use a disk file, we need to decide the following about the file and its intended
purpose:
• Suitable name for the file.
• Data type to be stored.
• Purpose (reading, writing, or updating).
• Method of creating the file.
A filename is a unique string of character that helps identify a file on the disk. The length of a filename
and the characters allowed are dependent on the OS on which the java program is executed. A filename
may contain two parts, a primary name and an optional period with extension. Example:
[Link]
[Link]
[Link]
Example:
//The program demonstrates the way of creating a new file by using file() constructor and
[Link]() method of file class.

import [Link]; // Import the File class

import [Link]; // Import IOException to handle errors

public class CreateFile {

public static void main(String[] args) {

try {

File myObj = new File("[Link]"); // Create File object

if ([Link]()) { // Try to create the file

[Link]("File created: " + [Link]());

} else {

[Link]("File already exists.");

} catch (IOException e) {

[Link]("An error occurred.");

[Link](); // Print error details

Reading/ Writing Characters

In Java, character streams are used to read and write text data (Unicode characters).
These streams automatically handle character encoding and decoding.

Character stream classes belong to the packages:

• [Link]
• [Link]

Reader and Writer subclasses are used for handling characters in files are FileReader (for reading
charaters) and FileWriter(for writing character).

//Program: Copy content from one file to another (character by character)


import [Link].*;
public class CopyCharacters {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]");
int ch;
while ((ch = [Link]()) != -1) {
[Link](ch);
}
[Link]();
[Link]();
[Link]("File copied successfully!");
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
Reading / Writing Bytes
Two commonly used classes for handling files are FileInputStream (Reading bytes from file) and
FileOutputStream (Writing bytes to file).
// Program: Copy File Using Byte Streams (Binary File Copy)
import [Link].*;
public class CopyBytes {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("[Link]");
FileOutputStream fos = new FileOutputStream("[Link]");
int b;
while ((b = [Link]()) != -1) { //Reads and write bytes till the end of the file.
[Link](b);
}
[Link]();
[Link]();
[Link]("File copied successfully!");
} catch (IOException e) {
[Link]([Link]());
}
}
}
Handling Primitive Types

The basic input and output streams provide read and write methods that can only be used for
reading/writing bytes or characters. If we want to read and write the primitive data types such as integers
and doubles, we can use filter classes as wrappers on existing input and output streams to filter data in the
original stream. The two filter classes used for creating data streams for handling primitive data types are
DataInputStream and DataOutputStream.

A data stream for input can be created as follows:

DataInputStream dis = new DataInputStream(new FileInputStream(inFile));

Similarly, a data stream for output can be created as follows:

DataOutputStream dos = new DataOutputStream(new FileOutputStream(oFile));

The following program demonstrates the use of data streams for reading and writing primitive data types.
The program first creates [Link] file and then writes a few primitive data types into it using
DataOutputStream. At the end of writing, the stream is closed. The program also creates a
DataInputStream, connects it to [Link] file and displays them on the screen. Finally, it closes the stream.
See the program below:

import [Link].*;
public class FileTest {
public static void main(String[] args) throws IOException {
File f = new File("[Link]");
DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));

// Write primitive data


[Link](2019);
[Link](true);
[Link]('S');
[Link](99.95);
[Link]();

DataInputStream dis = new DataInputStream(new FileInputStream(f));

// Read primitive data


[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]();
}
}
Output:
C:\file>java File09
2019
true
S
81.95
Concatenation and Buffering files
Concatenation means combining two or more files into a single file. This is achieved using
SequenceInputStream class.
Java supports creation of buffers to store temporarily data that is read from or written to a stream. This
process is called buffered I/O operation. Buffers can be created using BufferedInputStream and
BufferedOutputStream.

//Program: Concatenate files with buffering

import [Link].*;
class BufferedConcatenate {
public static void main(String[] args) throws Exception {

// Open file1 with a BufferedInputStream (faster reading)


BufferedInputStream b1 = new BufferedInputStream(
new FileInputStream("[Link]"));

// Open file2 with a BufferedInputStream


BufferedInputStream b2 = new BufferedInputStream(
new FileInputStream("[Link]"));

// SequenceInputStream joins both input streams (b1 first, then b2)


SequenceInputStream sis = new SequenceInputStream(b1, b2);

// BufferedOutputStream is used for fast writing to output file


BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("[Link]"));

int ch; // variable to store each byte read

// Read data from the sequence stream until end of both files
while ((ch = [Link]()) != -1) {
// Write the byte read into the output file
[Link](ch);
}

// Close all streams to release system resources


[Link](); // closes the sequence stream
[Link](); // flushes buffer and closes output stream

[Link]("Buffered concatenation done.");


}
}
Random access files
The random accessfile class supported by the [Link] allows us to create files that can be used for
reading or writing data with random access. Using this, we can read or write at any position within the file.
Such files are called Random access files.
• Reading from any position in a file
• Writing at any position in a file
• Moving the file pointer forward or backward
• Useful for large files where sequential access is slow

Mode Meaning
"r" Read only
"rw" Read + Write
"rws" Both data and metadata are written immediately to disk
"rwd" Only data is written immediately (metadata may be cached)

Program: Updating a Specific Location in File


import [Link].*;
class UpdatePosition {
public static void main(String[] args) throws Exception {
RandomAccessFile raf = new RandomAccessFile("[Link]", "rw");
[Link]("ABCDEF"); // Write 6 characters
[Link](2); // Move pointer to 3rd byte (0,1,2)
[Link]('Z'); // Replace 'C' with 'Z'
[Link]();
}
}
Interactive Input and Output
The process of reading data from the keyboard and displaying output in the screen is known as
Interactive I/O.
There are two types:
1. Simple Interactive I/O: which involves simple input from the keyboard and simple output to the text
form.
2. Graphical interactive I/O: which involves input from the various input devices and output to a
graphical environment on frames and applets.
//Simple Interactive input and output
import [Link].*;
import [Link];
public class NameMarksFile {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner([Link]);
// Taking input from user
[Link]("Enter student name: ");
String name = [Link]();
[Link]("Enter marks: ");
int marks = [Link]();
// Writing to file
FileWriter fw = new FileWriter("[Link]");
BufferedWriter bw = new BufferedWriter(fw);
[Link]("Name: " + name);
[Link]();
[Link]("Marks: " + marks);
[Link]();
[Link]();
[Link]("\nData written to file.\n");
// Reading from file
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
String line;
[Link]("Reading data from file:");
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
[Link]();
}
}
OUTPUT:
Enter student name: Chaitra
Enter marks: 92
Data written to file.
Reading data from file:
Name: Chaitra
Marks: 92
Other Stream classes

1. Object Streams (ObjectInputStream & ObjectOutputStream)

Object streams are high-level streams that allow entire Java objects to be written to a stream or file and
read back later. This mechanism is known as Object Serialization.

Class Purpose
ObjectOutputStream Writes objects to output stream
ObjectInputStream Reads objects from input stream

2. Piped Streams (PipedInputStream & PipedOutputStream)


Piped streams are used for communication between two threads. One thread writes data into the pipe,
and another thread reads it.
Class Description
PipedInputStream Receives data from a connected PipedOutputStream
PipedOutputStream Sends data into a connected PipedInputStream

3. Pushback Streams (PushbackInputStream & PushbackReader)

Pushback streams allow a program to look ahead in the input stream and push characters or bytes
back into the stream when needed.

Example:

• While reading number "123a", when 'a' comes, push it back because it begins next token.

Class Purpose
PushbackInputStream Pushback for byte streams
PushbackReader Pushback for character streams

You might also like