Unit:5 MANAGING INPUT /
OUTPUT FILES IN JAVA
Concepts of Streams- Stream Classes – Byte Stream classes – Character stream classes – Using
streams – I/O Classes – File Class – I/O exceptions – Creation of files – Reading / Writing
characters, Byte-Handling Primitive data Types – Random Access Files.
Introduction to File Processing in Java
we have used variables and arrays to store data in programs.
However, this approach has some limitations:
1. Temporary storage: When a variable goes out of its scope or the program ends, data is
lost.
Difficulty handling large data: Managing large amounts of data using variables and
arrays is cumbersome.
Persistent Storage
To overcome these problems, we can store data in secondary storage devices like floppy
disks or hard disks.
Data in these devices is stored as files.
Data stored in files is often called persistent data.
File and Record Structure
A file is a collection of related records stored at a specific location on a disk.
A record consists of multiple fields.
A field is a collection of characters.
Example:
Record → Field1, Field2, Field3
Field → Collection of characters
Character Representation in Java
Java uses Unicode characters.
Each character is represented by 2 bytes (16 bits), which is a combination of 0s and 1s.
Here’s a clear English notes version of the text you shared, formatted for study:
File Processing
File processing refers to storing and handling data using files.
Operations in file processing include:
o Creating files
o Updating files
o Reading and writing data
Java File Handling Features
Java provides powerful features for input/output using files:
o You can read/write data at the byte level, character level, or field/record level.
o Java also allows reading/writing class objects directly.
o Object Serialization: The process of reading and writing objects is called object
serialization.
o A record in a file can be represented as a class object in Java.
Summary
Variables and arrays are temporary and not ideal for large data.
Files provide persistent storage for data.
Java allows flexible file handling, including working with bytes, characters, fields, and
objects.
Object serialization enables storing class objects in files.
Concept of Stream in Java
🔹 Definition
A Stream in Java represents a sequence of data.
It is used to perform input and output (I/O) operations between a program and an
external source like a file, keyboard, or network.
Types of Streams:
Java divides streams into two main categories:
1. Byte Streams
Used to handle binary data (like images, audio, videos, etc.).
Read/write data byte by byte (8-bit).
Classes:
o FileInputStream
o FileOutputStream
o BufferedInputStream
o BufferedOutputStream
2. Character Streams
Used to handle text data (characters).
Read/write data character by character (16-bit Unicode).
Classes:
o FileReader
o FileWriter
o BufferedReader
o BufferedWriter
🔹 Basic Flow of Stream Operations:
Source → InputStream → Program → OutputStream → Destination
🔹 Examples:
Example 1: Reading a file
FileInputStream fin = new FileInputStream("data.txt");
int i;
while((i = fin.read()) != -1) {
System.out.print((char)i);
}
fin.close();
Example 2: Writing to a file
FileOutputStream fout = new FileOutputStream("output.txt");
String s = "Hello Java Streams!";
fout.write(s.getBytes());
fout.close();
BYTE STREAMS
🔹 Definition
Byte Streams are used to perform input and output operations on 8-bit binary data.
They are ideal for non-text files, such as:
Images (like .jpg, .png)
Audio files (like .mp3)
Video files (like .mp4)
Binary files or executables
They work at the lowest level of data — transferring raw bytes (0s and 1s) between a program
and an external source/destination.
🔹 Hierarchy of Byte Stream Classes
All byte stream classes belong to the java.io package and are derived from two abstract classes:
InputStream ←— (for reading bytes)
OutputStream ←— (for writing bytes)
These two are base classes, and all other byte stream classes extend them.
InputStream OutputStream
| |
-------------------------------- ------------------------------
| | | | | |
FileInputStream BufferedInputStream FileOutputStream BufferedOutputStream
|
DataInputStream DataOutputStream
Common Byte Stream Classes
1️⃣ FileInputStream
Used to read bytes from a file.
📍 Key Points:
Reads data byte by byte from a file.
Commonly used when reading binary files.
Throws an exception if the file doesn’t exist.
Syntax:
FileInputStream fin = new FileInputStream("input.jpg");
Example:
import java.io.*;
class ReadFile {
public static void main(String args[]) throws IOException {
FileInputStream fin = new FileInputStream("input.txt");
int i;
while((i = fin.read()) != -1) {
System.out.print((char)i); // converts byte to char for display
}
fin.close();
}
}
2️ FileOutputStream
Used to write bytes to a file.
📍 Key Points:
Creates a new file (if not exists) or overwrites the existing one.
Writes data byte by byte.
Useful for writing binary or text data.
Syntax:
FileOutputStream fout = new FileOutputStream("output.txt");
Example:
import java.io.*;
class WriteFile {
public static void main(String args[]) throws IOException {
FileOutputStream fout = new FileOutputStream("output.txt");
String s = "Hello, Byte Stream Example!";
byte b[] = s.getBytes(); // converts string to bytes
fout.write(b);
fout.close();
System.out.println("File written successfully!");
}
}
3️ BufferedInputStream
Used to read bytes efficiently using a buffer.
📍 Key Points:
Reads a block of bytes at once and stores it in a buffer (memory area).
Reduces the number of disk reads → faster performance.
Usually used on top of FileInputStream.
Syntax:
BufferedInputStream bin = new BufferedInputStream(new FileInputStream("input.txt"));
Example:
import java.io.*;
class BufferedRead {
public static void main(String args[]) throws IOException {
FileInputStream fin = new FileInputStream("input.txt");
BufferedInputStream bin = new BufferedInputStream(fin);
int i;
while((i = bin.read()) != -1) {
System.out.print((char)i);
}
bin.close();
fin.close();
}
}
4️ BufferedOutputStream
Used to write bytes efficiently using a buffer.
📍 Key Points:
Stores data temporarily in a buffer before writing it to disk.
Reduces the number of physical write operations.
Increases efficiency when writing large data.
Syntax:
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("output.txt"));
Example:
import java.io.*;
class BufferedWrite {
public static void main(String args[]) throws IOException {
FileOutputStream fout = new FileOutputStream("output.txt");
BufferedOutputStream bout = new BufferedOutputStream(fout);
String s = "Buffered Output Stream Example";
byte b[] = s.getBytes();
bout.write(b);
bout.flush(); // ensures all data is written
bout.close();
fout.close();
System.out.println("Data written successfully using buffer!");
}
}
💡 Advantages of Byte Streams
✅ Suitable for binary data (non-text files)
✅ Can handle any type of file — not just text
✅ Buffered streams improve performance
✅ Simple to use and consistent with Java’s I/O model
🚫 Limitations
❌ Byte streams are not suitable for text files (because text needs Unicode character handling)
❌ Reading character data byte-by-byte may cause encoding issues
2. CHARACTER STREAMS
🔹 Definition
Character Streams are used to read and write text data (characters) instead of raw bytes.
They automatically handle Unicode (16-bit) characters, making them ideal for text files such
as .txt, .html, .xml, etc.
In simple words —
👉 Byte Streams → For binary data (images, audio)
👉 Character Streams → For text data (letters, words, sentences)
🔹 Why Character Streams?
When we use Byte Streams for text files, it reads bytes and may not properly interpret characters
(especially Unicode characters).
So, Character Streams are introduced to handle text in a platform-independent way.
They use Reader and Writer as base classes.
🔹 Hierarchy of Character Streams
Reader ←— for reading characters
Writer ←— for writing characters
All other character stream classes are subclasses of these two abstract classes.
🧩 Common Character Stream Classes
Class Description
FileReader Reads characters from a file
FileWriter Writes characters to a file
BufferedReader Reads characters efficiently using a buffer
BufferedWriter Writes characters efficiently using a buffer
CharArrayReader Reads data from a character array
CharArrayWriter Writes data to a character array
InputStreamReader Converts byte stream to character stream
OutputStreamWriter Converts character stream to byte stream
🧱 1️⃣ FileReader Class
🔸 Purpose:
Used to read characters from a text file.
🔸 Key Points:
Automatically converts bytes from the file into characters.
If file not found → throws FileNotFoundException.
Can read data character by character.
Syntax:
FileReader fr = new FileReader("input.txt");
Example:
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("input.txt");
int ch;
while((ch = fr.read()) != -1) {
System.out.print((char)ch);
}
fr.close();
}
}
🟩 Output:
(Displays all text content from input.txt)
🧱 2️FileWriter Class
🔸 Purpose:
Used to write characters to a text file.
🔸 Key Points:
Writes data character by character.
If the file doesn’t exist, it creates one automatically.
By default, it overwrites existing data (can append using a second parameter).
Syntax:
FileWriter fw = new FileWriter("output.txt");
Example:
import java.io.*;
class FileWriterDemo {
public static void main(String args[]) throws IOException {
FileWriter fw = new FileWriter("output.txt");
fw.write("Welcome to Character Streams in Java!");
fw.close();
System.out.println("Data written successfully.");
}
}
🧱 3️BufferedReader Class
🔸 Purpose:
Used to read characters, lines, or arrays efficiently from a text file.
🔸 Key Points:
Uses an internal buffer for faster reading.
Supports a special method readLine() to read entire lines.
Must be connected to a Reader object (like FileReader).
Syntax:
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
Example:
import java.io.*;
class BufferedReaderDemo {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
🟩 Output:
Displays each line of text file on the console.
🧱 4️BufferedWriter Class
🔸 Purpose:
Used to write characters or strings efficiently to a text file.
🔸 Key Points:
Uses buffering to improve performance.
You can use newLine() to move to the next line.
Must call flush() before closing to ensure all data is written.
Syntax:
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
Example:
import java.io.*;
class BufferedWriterDemo {
public static void main(String args[]) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
bw.write("Java Character Streams Example");
bw.newLine(); // moves to next line
bw.write("BufferedWriter makes writing faster!");
bw.flush(); // ensure data is written to file
bw.close();
System.out.println("File written successfully!");
}
}
🟩 Output:
Creates output.txt containing:
Java Character Streams Example
BufferedWriter makes writing faster!
💡 Advantages of Character Streams
✅ Automatically handles Unicode text
✅ Suitable for text files
✅ Supports line-by-line reading using readLine()
✅ More efficient with buffering (BufferedReader, BufferedWriter)
✅ Simple and easy to use for all text-based applications
⚠️Limitations
❌ Not suitable for binary data (images, audio, etc.)
❌ Slightly slower than byte streams when dealing with raw data
BYTE STREAM CLASSES IN JAVA
1️⃣ Introduction
Byte Stream classes are used for reading and writing data in bytes (8-bit data).
They are suitable for binary data such as images, audio, video, executable files, etc.
All byte stream classes are derived from two abstract classes:
o InputStream
o OutputStream
🟢 InputStream (Base Class for Byte Input)
Used for reading bytes from a source (like a file, network, array, etc.)
Common methods:
int read(); // reads one byte
int read(byte[] b); // reads bytes into array
void close(); // closes input stream
Important subclasses of InputStream:
Class Description
FileInputStream Reads data from a file
ByteArrayInputStream Reads data from a byte array
StringBufferInputStream Reads data from a string buffer (deprecated, replaced by
StringReader)
PipedInputStream Used for reading data from a pipe (inter-thread communication)
SequenceInputStream Combines multiple input streams into one
FilterInputStream Allows filtering data as it is read
🔹 1. FileInputStream
Used to read binary data from a file.
FileInputStream fin = new FileInputStream("data.txt");
int i;
while((i = fin.read()) != -1){
System.out.print((char)i);
}
fin.close();
Reads the file byte-by-byte.
🔹 2. SequenceInputStream
Used to combine multiple input streams into a single stream.
Data is read from the first stream until it ends, then from the next.
FileInputStream f1 = new FileInputStream("a.txt");
FileInputStream f2 = new FileInputStream("b.txt");
SequenceInputStream sis = new SequenceInputStream(f1, f2);
🔹 3. PipedInputStream
Used for thread communication.
Data written by one thread to PipedOutputStream can be read by another using
PipedInputStream.
PipedInputStream pin = new PipedInputStream();
PipedOutputStream pout = new PipedOutputStream(pin);
🔹 4. ByteArrayInputStream
Used to read data from a byte array as an input source.
byte[] arr = {65, 66, 67};
ByteArrayInputStream bin = new ByteArrayInputStream(arr);
🔹 5. StringBufferInputStream
Used to read data from a string buffer as a byte stream.
(⚠️Deprecated — use StringReader instead)
StringBufferInputStream sb = new StringBufferInputStream("Hello");
🔹 6. FilterInputStream
It is a superclass for all classes that filter input data.
Examples:
o BufferedInputStream
o DataInputStream
o PushbackInputStream
🔸 FilterInputStream is divided into three types:
Subclass Description
BufferedInputStream Improves performance by buffering input data.
PushbackInputStrea Allows a byte to be pushed back into the stream.
m
DataInputStream Allows reading Java primitive data types (int, float, etc.) from the
stream.
🔵 OutputStream (Base Class for Byte Output)
Used for writing bytes to a destination (file, array, network, etc.)
Common methods:
void write(int b);
void write(byte[] b);
void close();
Important Subclasses of OutputStream
Class Description
FileOutputStream Writes data to a file
ByteArrayOutputStrea Writes data to a byte array
m
PipedOutputStream Sends data to a PipedInputStream
FilterOutputStream Filters output data
BufferedOutputStream Buffers data before writing
DataOutputStream Writes Java primitive data types
Summary Table
Input Stream Class Purpose
FileInputStream Read from a file
ByteArrayInputStream Read from a byte array
StringBufferInputStream Read from a string buffer
PipedInputStream Read from a pipe
SequenceInputStream Combine multiple input streams
FilterInputStream Filter data (Buffered, Pushback, Data)
Output Stream Class Purpose
FileOutputStream Write to a file
ByteArrayOutputStream Write to a byte array
PipedOutputStream Write to a pipe
FilterOutputStream Filter output data
Byte Stream Methods in Java
🌿 1️⃣ InputStream Class Methods
Method Description
int read() Reads one byte of data from the input stream. Returns -1 if the
end of the stream is reached.
int read(byte[] b) Reads multiple bytes from the stream and stores them in the array
b. Returns the number of bytes read.
int read(byte[] b, int off, Reads up to len bytes into array b starting from offset off.
int len)
long skip(long n) Skips (ignores) n bytes of input.
int available() Returns the number of bytes available to read without blocking.
void close() Closes the stream and releases system resources.
void mark(int readlimit) Marks the current position in the input stream.
void reset() Resets the stream to the position last marked by mark().
boolean markSupported() Returns true if the stream supports mark and reset methods.
✅ Example
FileInputStream fin = new FileInputStream("data.txt");
int i;
while((i = fin.read()) != -1) {
System.out.print((char)i);
}
fin.close();
📘 Here:
read() → reads one byte at a time
close() → closes the stream after reading
🌿 2️⃣ OutputStream Class Methods
Method Description
void write(int b) Writes one byte to the output stream.
void write(byte[] b) Writes all bytes from array b to the output stream.
void write(byte[] b, int off, int Writes len bytes from array b starting at offset off.
len)
void flush() Forces any buffered output bytes to be written
immediately.
void close() Closes the output stream and releases system resources.
✅ Example
FileOutputStream fout = new FileOutputStream("data.txt");
String s = "Hello Java";
byte[] b = s.getBytes();
fout.write(b);
fout.close();
📘 Here:
write() → writes byte data to the file
close() → closes the file stream after writing
🌼 Summary Table
Category Important Methods
InputStream read(), read(byte[]), skip(), available(), close(), mark(),
reset()
OutputStream write(), write(byte[]), flush(), close()
Using Streams in Java
🔹 Concept Overview
A Stream in Java is a pipeline for data flow.
It connects a data source (like a file, keyboard, or network) to a program or destination
(like a file or screen).
Streams are used for Input (reading) and Output (writing) operations.
🧩 Types of Streams
Type Purpose
Input Stream To read data from a source
Output Stream To write data to a
destination
🧱 Steps for Using a Stream
To perform I/O using streams, follow three main steps:
1️⃣ Create a Stream
Connect the stream to a physical source or destination.
Examples:
FileInputStream fin = new FileInputStream("input.txt");
FileOutputStream fout = new FileOutputStream("output.txt");
2️⃣ Perform Read/Write Operations
Use stream methods to read or write data.
✅ Example: Reading data
int i;
while((i = fin.read()) != -1) {
System.out.print((char)i);
}
✅ Example: Writing data
String s = "Hello Java Stream";
byte[] b = s.getBytes();
fout.write(b);
3️⃣ Close the Stream
After operations, always close the stream to free system resources.
fin.close();
fout.close();
⚙️Full Example: Copying Data Using Streams
import java.io.*;
class CopyFile {
public static void main(String args[]) throws Exception {
FileInputStream fin = new FileInputStream("input.txt");
FileOutputStream fout = new FileOutputStream("output.txt");
int i;
while((i = fin.read()) != -1) {
fout.write(i);
}
fin.close();
fout.close();
System.out.println("File copied successfully!");
}
}
Explanation:
FileInputStream reads bytes from input.txt
FileOutputStream writes those bytes to output.txt
Data flows from input → program → output through streams
📘 Advantages of Using Streams
1. Uniform I/O handling for all data sources.
2. Supports chaining (for filtering data).
3. Provides buffering and data-type support.
4. Automatic resource management with try-with-resources.
🧠 Explanation
Part Description
try (...) Creates the InputStream and OutputStream. These
resources are automatically closed when the block ends.
fin.read() Reads one byte at a time from input.txt. Returns -1 when
end of file is reached.
fout.write(i) Writes the read byte to output.txt.
System.out.println("Copied Prints success message after copying.
successfully!");
catch (IOException e) Handles any file I/O errors (for example, file not found).
✅ No need for close() — Java automatically closes both streams when the try block finishes.
Copied successfully!
I/O Classes in Java
1. Introduction to I/O Classes
Java provides classes to handle input and output (I/O) operations. These classes are available in
the java.io package.
I/O classes allow us to:
Read data from sources (keyboard, file, network)
Write data to destinations (console, file, network)
There are two main types:
1. Byte Stream Classes – Handle data in bytes (binary data).
Examples: InputStream, OutputStream, FileInputStream, FileOutputStream.
2. Character Stream Classes – Handle data in characters (text data).
Examples: Reader, Writer, FileReader, FileWriter.
Diagram:
java.io Package
/ \
Byte Streams Character Streams
(binary) (text)
2. File Class in Java
The File class represents a file or directory in Java.
It does not directly read or write data but provides methods to:
Create, delete files/directories
Get file information (name, path, size, permissions)
Check file existence
Syntax:
File file = new File("example.txt");
Common Methods:
Method Description
exists() Checks if the file exists
createNewFile() Creates a new file
delete() Deletes a file
isFile() Checks if it is a file
isDirectory() Checks if it is a directory
length() Returns the size of file in bytes
getName() Returns file name
getAbsolutePath() Returns full path
Reading and Writing Characters and Bytes in Java
1. Reading and Writing Characters
Classes for Character I/O:
o FileReader → Read characters from a file
o FileWriter → Write characters to a file
Key Points:
o Used for text files
o Reads/writes character by character or string by string
2. Reading and Writing Bytes
Classes for Byte I/O:
o FileOutputStream → Write bytes to a file
o FileInputStream → Read bytes from a file
Key Points:
o Used for binary files (images, audio, video, or primitive data)
o Reads/writes byte by byte
3. Differences Between Characters and Bytes
Feature Character I/O Byte I/O
Classes FileReader/FileWriter FileInputStream/FileOutputStream
Data Type Characters (text) Bytes (binary)
Use Case Text files Binary files, images, audio, primitive data
Method Example read(), write() read(), write()
I/O Exceptions in Java
Whenever file operations fail, Java throws exceptions. Most common are:
1. IOException – General input/output error
2. FileNotFoundException – File not found
3. EOFException – End of file reached unexpectedly
4. InterruptedIOException – Thread interrupted during I/O
Example using exception handling:
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class IOExceptionExample {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("nonexistent.txt");
fr.close();
} catch (FileNotFoundException e) {
System.out.println("File not found error!");
} catch (IOException e) {
System.out.println("General I/O error");
}
}
}
Output:
File not found error!
Key Points:
Always handle exceptions when performing file I/O.
Use try-catch blocks or declare throws in method signature.
IOException is a checked exception, so compiler forces handling it.
4. Summary
I/O Classes: Handle reading/writing data (byte & character streams).
File Class: Represents files/directories, provides metadata and management methods.
I/O Exceptions: Errors during I/O operations must be handled (checked exceptions).
Exceptions in Java
1. What is an Exception?
An exception is an unexpected problem that occurs during program execution.
It disrupts the normal flow of the program.
Example: Dividing by zero, reading a file that does not exist, invalid input, etc.
Flow:
Normal Flow → Exception Occurs → Exception Handling → Program Continues or Terminates
Types of Exceptions:
1. Checked Exception: Must be handled at compile time (IOException, SQLException)
2. Unchecked Exception: Occurs at runtime (ArithmeticException, NullPointerException)
Input/Output Exceptions
I/O operations may fail due to reasons like missing files, unavailable devices, etc.
Java provides IOException and its subclasses to handle such problems.
Common I/O Exceptions:
Exception Cause
IOException General I/O failure
FileNotFoundException File not found
EOFException End of file reached unexpectedly
Handling Exceptions
a) try-catch block
The try block contains code that might throw an exception.
The catch block handles the exception.
Syntax:
try {
// code that may throw exception
} catch (ExceptionType e) {
// code to handle exception
}
b) throw keyword
The throw keyword is used to explicitly throw an exception.
Can throw built-in or custom exceptions.
Syntax:
throw new ExceptionType("Error message");
public class MiniException {
public static void main(String[] args) {
try {
throw new ArithmeticException("Something went wrong!");
} catch(ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
}
System.out.println("Program continues.");
}
}
Output
Caught: Something went wrong!
Program continues.
✅ Explanation:
1. throw → explicitly throws an exception.
2. try → contains the code that may throw an exception.
3. catch → handles the exception so the program does not crash.
4. Summary Table
Keyword Use
try Code that may throw exception
catch Handle exception
throw Explicitly throw an exception
throws Declare that a method may throw exception
Key Points:
IOException is a checked exception → must be handled.
ArithmeticException is unchecked → optional to handle.
Always use try-catch for I/O operations like file reading/writing.
Handling Primitive Data Types in Java File I/O
1. Introduction
Primitive data types in Java: int, float, double, char, boolean, long, short, byte.
To write/read primitive data types to/from a file, we use byte streams:
o DataOutputStream → for writing
o DataInputStream → for reading
Unlike FileWriter/FileReader (character-based), these store data in binary format,
which is more compact and efficient.
2. Key Classes
Class Purpose
DataOutputStrea Write primitive data types to a file in binary
m
DataInputStream Read primitive data types from a file in binary
FileOutputStream Used with DataOutputStream for output
FileInputStream Used with DataInputStream for input
3. Key Methods
Writing Data:
writeInt(int i)
writeFloat(float f)
writeDouble(double d)
writeChar(char c)
writeBoolean(boolean b)
writeBytes(String s)
Reading Data:
readInt()
readFloat()
readDouble()
readChar()
readBoolean()
readUTF() // reads a string in UTF format
5. Key Points
1. DataOutputStream and DataInputStream handle primitive types efficiently in binary
format.
2. Use FileOutputStream/FileInputStream as the underlying stream.
3. Order matters: Read data in the same order as written.
4. IOException must be handled using try-catch.
5. writeUTF() / readUTF() is used for string data in binary format.
Random Access Files in Java
1. Introduction
RandomAccessFile class in Java allows you to read and write at any position in a file.
Unlike sequential reading/writing (FileReader/FileWriter), you do not need to read
from the beginning to access a particular part of the file.
Useful for databases, record-based files, large files.
Constructor Syntax:
RandomAccessFile raf = new RandomAccessFile("filename.txt", "mode");
Modes:
"r" → read-only
"rw" → read and write
Key Methods of RandomAccessFile
Method Purpose
seek(long pos) Move file pointer to specified position
read() Read a byte
readInt() Read an integer
readChar() Read a character
readLine() Read a line of text
write(int b) Write a byte
writeInt(int i) Write an integer
writeChar(char c) Write a character
writeBytes(String s) Write a string in bytes
Additional Method:
getFilePointer() → Returns current pointer position in file
Simple Example
import java.io.RandomAccessFile;
import java.io.IOException;
public class RandomAccessExample {
public static void main(String[] args) {
try {
// Open file in read/write mode
RandomAccessFile raf = new RandomAccessFile("random.txt", "rw");
// Write data
raf.writeUTF("Hello");
raf.writeInt(100);
// Move pointer to start
raf.seek(0);
// Read data
System.out.println("String: " + raf.readUTF());
System.out.println("Integer: " + raf.readInt());
raf.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Output:
String: Hello
Integer: 100
4. Key Points
1. RandomAccessFile supports non-sequential access.
2. Can read/write different data types (int, char, string, byte).
3. Always use seek() to move the pointer to the required position.
4. Can be opened in "r" (read) or "rw" (read/write) mode.
5. Useful for applications requiring direct access to specific records.