So far the operations using Java programs are done on a prompt/terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file.
What is File Handling in Java?
A file is a container that is used to store various types of information. Data is permanently stored in secondary memory by creating a file with a unique name. A file may consist of text, image or any other document.
Different operations that can be performed on a file are:
- Creation of a new file
- Opening an existing file
- Reading from file
- Writing to a file
- Moving to a specific location in a file
- Closing a file
Different classes that can be used in Java for File Handling:
- InputStream
- OutputStream
- FilterOutputStream
- FileOutputStream
- ByteArrayOutputStream
- ByteArrayInputStream
- FileInputStream
- FilterInputStream
- StringBufferInputStream
- SequenceInputStream
- BufferedOutputStream
- StringBufferInputStream
- DataOutputStream
- PrintStream
- BufferedInputStream
- DataInputStream
- PushbackInputStream
In this article, we will learn how Java ByteStreams are used to perform input and output of 8-bits(1 byte) using class RandomAccessFile which consists of method writeBytes() and readBytes() to write and read the data in the form of bytes.
Various Methods used to perform File operation:
- writeBytes(String s): Writes the string to the file as a sequence of bytes.
- readLine(): Reads the next line of text from this file.
- getFilePointer(): Returns the current offset in this file.
- length(): Returns the length of this file and return type is long.
- close(): Closes this random access file stream and releases any system resources associated with the stream.
- setLength(long newLength): Sets the length of this file.
- seek(long pos): Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
File opening modes in Java:
Value | Meaning |
---|
“r” | Open for reading only. Invoking any of the write methods of the resulting object will cause an IOException to be thrown. |
“rw” | Open to reading and writing. If the file does not already exist then an attempt will be made to create it. |
“rws” | Open for reading and writing, as with “rw”, and also require that every update to the file’s content or metadata be written synchronously to the underlying storage device. |
“rwd” | Open for reading and writing, as with “rw”, and also require that every update to the file’s content be written synchronously to the underlying storage device. |
Syntax of Opening File using RandomAccessFile:
File file = new File( filename )
RandomAccessFile raf = new RandomAccessFile(file, mode)
CRUD operations using File Handling in Java
Example: Consider that you want to keep records of your friend’s contact number in a file. To distinguish between your friend’s name and contact number you need a separator. To do, so you need to select a separator such as ‘!’ or ‘$’ or some special symbol which does not appear in your friend’s name. Then we will form a string consist of a name, special symbol and number to insert into the file.
Syntax of a Contact in the file friendsContact.txt:
Name!Number
How to Create a File in Java?
Java
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class AddFriend {
public static void main(String data[])
{
try {
String newName = data[ 0 ];
long newNumber = Long.parseLong(data[ 1 ]);
String nameNumberString;
String name;
long number;
int index;
File file = new File( "friendsContact.txt" );
if (!file.exists()) {
file.createNewFile();
}
RandomAccessFile raf
= new RandomAccessFile(file, "rw" );
boolean found = false ;
while (raf.getFilePointer() < raf.length()) {
nameNumberString = raf.readLine();
String[] lineSplit
= nameNumberString.split( "!" );
name = lineSplit[ 0 ];
number = Long.parseLong(lineSplit[ 1 ]);
if (name == newName
|| number == newNumber) {
found = true ;
break ;
}
}
if (found == false ) {
nameNumberString
= newName + "!"
+ String.valueOf(newNumber);
raf.writeBytes(nameNumberString);
raf.writeBytes(System.lineSeparator());
System.out.println( " Friend added. " );
raf.close();
}
else {
raf.close();
System.out.println( " Input name"
+ " does not exists. " );
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
catch (NumberFormatException nef) {
System.out.println(nef);
}
}
}
|
Output:
Compiling and Adding the contact in the newly created file:
javac AddFriend.java
java AddFriend abc 1111111111
Friend added
java AddFriend pqr 1111111111
Input name or number already exist
File:

How to Read a File in Java?
Java
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class DisplayFriends {
public static void main(String data[])
{
try {
String nameNumberString;
String name;
long number;
int index;
File file = new File( "friendsContact.txt" );
if (!file.exists()) {
file.createNewFile();
}
RandomAccessFile raf
= new RandomAccessFile(file, "rw" );
boolean found = false ;
while (raf.getFilePointer() < raf.length()) {
nameNumberString = raf.readLine();
String[] lineSplit
= nameNumberString.split( "!" );
name = lineSplit[ 0 ];
number = Long.parseLong(lineSplit[ 1 ]);
System.out.println(
"Friend Name: " + name + "\n"
+ "Contact Number: " + number + "\n" );
}
catch (IOException ioe)
{
System.out.println(ioe);
}
catch (NumberFormatException nef)
{
System.out.println(nef);
}
}
}
|
Output:
Compiling and reading the contacts from the file:
javac DisplayFriends.java
java DisplayFriends
Friend Name: abc
Contact Number: 1234567890
Friend Name: lmn
Contact Number: 3333333333
Friend Name: xyz
Contact Number: 4444444444
File:

How to Update a File in Java?
Java
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class UpdateFriend {
public static void main(String data[])
{
try {
String newName = data[ 0 ];
long newNumber = Long.parseLong(data[ 1 ]);
String nameNumberString;
String name;
long number;
int index;
File file = new File( "friendsContact.txt" );
if (!file.exists()) {
file.createNewFile();
}
RandomAccessFile raf
= new RandomAccessFile(file, "rw" );
boolean found = false ;
while (raf.getFilePointer() < raf.length()) {
nameNumberString = raf.readLine();
String[] lineSplit
= nameNumberString.split( "!" );
name = lineSplit[ 0 ];
number = Long.parseLong(lineSplit[ 1 ]);
if (name == newName
|| number == newNumber) {
found = true ;
break ;
}
}
if (found == true ) {
File tmpFile = new File( "temp.txt" );
RandomAccessFile tmpraf
= new RandomAccessFile(tmpFile, "rw" );
raf.seek( 0 );
while (raf.getFilePointer()
< raf.length()) {
nameNumberString = raf.readLine();
index = nameNumberString.indexOf( '!' );
name = nameNumberString.substring(
0 , index);
if (name.equals(inputName)) {
nameNumberString
= name + "!"
+ String.valueOf(newNumber);
}
tmpraf.writeBytes(nameNumberString);
tmpraf.writeBytes(
System.lineSeparator());
}
raf.seek( 0 );
tmpraf.seek( 0 );
while (tmpraf.getFilePointer()
< tmpraf.length()) {
raf.writeBytes(tmpraf.readLine());
raf.writeBytes(System.lineSeparator());
}
raf.setLength(tmpraf.length());
tmpraf.close();
raf.close();
tmpFile.delete();
System.out.println( " Friend updated. " );
}
else {
raf.close();
System.out.println( " Input name"
+ " does not exists. " );
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
catch (NumberFormatException nef) {
System.out.println(nef);
}
}
}
|
Output:
Compiling and updating the contact in the file:
javac UpdateFriend.java
java UpdateFriend abc 1234567890
Friend updated.
java UpdateFriend tqr
Input name does not exists.
File:

How to Delete a File in Java?
Java
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class DeleteFriend {
public static void main(String data[])
{
try {
String newName = data[ 0 ];
String nameNumberString;
String name;
long number;
int index;
File file = new File( "friendsContact.txt" );
if (!file.exists()) {
file.createNewFile();
}
RandomAccessFile raf
= new RandomAccessFile(file, "rw" );
boolean found = false ;
while (raf.getFilePointer() < raf.length()) {
nameNumberString = raf.readLine();
String[] lineSplit
= nameNumberString.split( "!" );
name = lineSplit[ 0 ];
number = Long.parseLong(lineSplit[ 1 ]);
if (name == newName) {
found = true ;
break ;
}
}
if (found == true ) {
File tmpFile = new File( "temp.txt" );
RandomAccessFile tmpraf
= new RandomAccessFile(tmpFile, "rw" );
raf.seek( 0 );
while (raf.getFilePointer()
< raf.length()) {
nameNumberString = raf.readLine();
index = nameNumberString.indexOf( '!' );
name = nameNumberString.substring(
0 , index);
if (name.equals(inputName)) {
continue ;
}
tmpraf.writeBytes(nameNumberString);
tmpraf.writeBytes(
System.lineSeparator());
}
raf.seek( 0 );
tmpraf.seek( 0 );
while (tmpraf.getFilePointer()
< tmpraf.length()) {
raf.writeBytes(tmpraf.readLine());
raf.writeBytes(System.lineSeparator());
}
raf.setLength(tmpraf.length());
tmpraf.close();
raf.close();
tmpFile.delete();
System.out.println( " Friend deleted. " );
}
else {
raf.close();
System.out.println( " Input name"
+ " does not exists. " );
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}
|
Output:
Compiling and deleting the contact in the file:
javac DeleteFriend.java
java DeleteFriend pqr
Friend deleted.
java DeleteFriend tqr
Input name does not exists.
File:

Create
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class AddFriend {
public static void main(String data[])
{
try {
String newName = data[ 0 ];
long newNumber = Long.parseLong(data[ 1 ]);
String nameNumberString;
String name;
long number;
int index;
File file = new File( "friendsContact.txt" );
if (!file.exists()) {
file.createNewFile();
}
RandomAccessFile raf
= new RandomAccessFile(file, "rw" );
boolean found = false ;
while (raf.getFilePointer() < raf.length()) {
nameNumberString = raf.readLine();
String[] lineSplit
= nameNumberString.split( "!" );
name = lineSplit[ 0 ];
number = Long.parseLong(lineSplit[ 1 ]);
if (name == newName
|| number == newNumber) {
found = true ;
break ;
}
}
if (found == false ) {
nameNumberString
= newName + "!"
+ String.valueOf(newNumber);
raf.writeBytes(nameNumberString);
raf.writeBytes(System.lineSeparator());
System.out.println( " Friend added. " );
raf.close();
}
else {
raf.close();
System.out.println( " Input name"
+ " does not exists. " );
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
catch (NumberFormatException nef) {
System.out.println(nef);
}
}
}
|
Read
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class DisplayFriends {
public static void main(String data[])
{
try {
String nameNumberString;
String name;
long number;
int index;
File file = new File( "friendsContact.txt" );
if (!file.exists()) {
file.createNewFile();
}
RandomAccessFile raf
= new RandomAccessFile(file, "rw" );
boolean found = false ;
while (raf.getFilePointer() < raf.length()) {
nameNumberString = raf.readLine();
String[] lineSplit
= nameNumberString.split( "!" );
name = lineSplit[ 0 ];
number = Long.parseLong(lineSplit[ 1 ]);
System.out.println(
"Friend Name: " + name + "\n"
+ "Contact Number: " + number + "\n" );
}
catch (IOException ioe)
{
System.out.println(ioe);
}
catch (NumberFormatException nef)
{
System.out.println(nef);
}
}
}
|
Update
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class UpdateFriend {
public static void main(String data[])
{
try {
String newName = data[ 0 ];
long newNumber = Long.parseLong(data[ 1 ]);
String nameNumberString;
String name;
long number;
int index;
File file = new File( "friendsContact.txt" );
if (!file.exists()) {
file.createNewFile();
}
RandomAccessFile raf
= new RandomAccessFile(file, "rw" );
boolean found = false ;
while (raf.getFilePointer() < raf.length()) {
nameNumberString = raf.readLine();
String[] lineSplit
= nameNumberString.split( "!" );
name = lineSplit[ 0 ];
number = Long.parseLong(lineSplit[ 1 ]);
if (name == newName
|| number == newNumber) {
found = true ;
break ;
}
}
if (found == true ) {
File tmpFile = new File( "temp.txt" );
RandomAccessFile tmpraf
= new RandomAccessFile(tmpFile, "rw" );
raf.seek( 0 );
while (raf.getFilePointer()
< raf.length()) {
nameNumberString = raf.readLine();
index = nameNumberString.indexOf( '!' );
name = nameNumberString.substring(
0 , index);
if (name.equals(inputName)) {
nameNumberString
= name + "!"
+ String.valueOf(newNumber);
}
tmpraf.writeBytes(nameNumberString);
tmpraf.writeBytes(
System.lineSeparator());
}
raf.seek( 0 );
tmpraf.seek( 0 );
while (tmpraf.getFilePointer()
< tmpraf.length()) {
raf.writeBytes(tmpraf.readLine());
raf.writeBytes(System.lineSeparator());
}
raf.setLength(tmpraf.length());
tmpraf.close();
raf.close();
tmpFile.delete();
System.out.println( " Friend updated. " );
}
else {
raf.close();
System.out.println( " Input name"
+ " does not exists. " );
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
catch (NumberFormatException nef) {
System.out.println(nef);
}
}
}
|
Delete
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class DeleteFriend {
public static void main(String data[])
{
try {
String newName = data[ 0 ];
String nameNumberString;
String name;
long number;
int index;
File file = new File( "friendsContact.txt" );
if (!file.exists()) {
file.createNewFile();
}
RandomAccessFile raf
= new RandomAccessFile(file, "rw" );
boolean found = false ;
while (raf.getFilePointer() < raf.length()) {
nameNumberString = raf.readLine();
String[] lineSplit
= nameNumberString.split( "!" );
name = lineSplit[ 0 ];
number = Long.parseLong(lineSplit[ 1 ]);
if (name == newName) {
found = true ;
break ;
}
}
if (found == true ) {
File tmpFile = new File( "temp.txt" );
RandomAccessFile tmpraf
= new RandomAccessFile(tmpFile, "rw" );
raf.seek( 0 );
while (raf.getFilePointer()
< raf.length()) {
nameNumberString = raf.readLine();
index = nameNumberString.indexOf( '!' );
name = nameNumberString.substring(
0 , index);
if (name.equals(inputName)) {
continue ;
}
tmpraf.writeBytes(nameNumberString);
tmpraf.writeBytes(
System.lineSeparator());
}
raf.seek( 0 );
tmpraf.seek( 0 );
while (tmpraf.getFilePointer()
< tmpraf.length()) {
raf.writeBytes(tmpraf.readLine());
raf.writeBytes(System.lineSeparator());
}
raf.setLength(tmpraf.length());
tmpraf.close();
raf.close();
tmpFile.delete();
System.out.println( " Friend deleted. " );
}
else {
raf.close();
System.out.println( " Input name"
+ " does not exists. " );
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}
|