Java File Handling (Input and Output) by Subodh Kumar

SubodhKumar223121 1 views 16 slides Nov 02, 2025
Slide 1
Slide 1 of 16
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16

About This Presentation

File handling in Java refers to the methods of reading from and writing data to files. It
allows Java programs to interact with files stored on a computer's storage, enabling persistent data storage and retrieval.


Slide Content

JAVA PROGRAMMING BY (

Created by Page 227 of 401




File: A file is a named location that can be used to store related information. For example, demo.java is
a Java file that contains information about the Java program.

File handling: File handling in Java refers to the methods of reading from and writing data to files. It
allows Java programs to interact with files stored on a computer's storage, enabling persistent data
storage and retrieval.
• The java.io package provides classes for performing file operations such as creating, opening,
reading, writing, and closing files.
• File handling is essential for applications that need to manage data, such as text editors,
databases, and configuration files.

Streams in Java: In Java, a sequence of data is known as a stream. This concept is used to perform I/O
operations on a file. Below are the types of Streams:

JAVA PROGRAMMING BY (

Created by Page 228 of 401

Types of Streams

✓ Depending on the type of operations, streams can be divided into two primary classes:


Input Stream: These streams are used to read data that must be taken as an input from a source array
or file or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream
etc.

Creating an InputStream:
FileInputStream obj = new FileInputStream(); // Here, an input stream is created using FileInputStream.

Common Methods of InputStream:
• read() : Reads one byte of data from the input stream.
• read(byte[] array) : Reads byte from the stream and stores that byte in the specified array.
• available() Returns the number of bytes available in the input stream.
• close() Closes the input stream.

Creating an OutputStream:
FileOutputStream obj = new FileOutputStream(); // Here, an output stream is created using
FileOutputStream.

Common Methods of OutputStream:

• write() : Writes the specified byte to the output stream.
• write(byte[] array : Writes the bytes which are inside a specific array to the output stream.
• close() : Closes the output stream.
• flush() : Forces to write all the data present in an output stream to the destination.

JAVA PROGRAMMING BY (

Created by Page 229 of 401


Output Stream: These streams are used to write data as outputs into an array or file or any output
peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc.




✓ Depending on the types of file, Streams can be divided into two primary classes which can be further
divided into other classes as can be seen through the diagram below followed by the explanations.

ByteStream:
This is used to process data byte by byte (8 bits). Though it has many classes, the FileInputStream and
the FileOutputStream are the most popular ones. The FileInputStream is used to read from the source
and FileOutputStream is used to write to the destination. Here is the list of various ByteStream Classes:

• BufferedInputStream It is used for Buffered Input Stream.

JAVA PROGRAMMING BY (

Created by Page 230 of 401

• DataInputStream It contains method for reading java standard datatypes.
• FileInputStream This is used to reads from a file
• InputStream This is an abstract class that describes stream input.
• PrintStream This contains the most used print() and println() method
• BufferedOutputStream This is used for Buffered Output Stream.
• DataOutputStream This contains method for writing java standard data types.
• FileOutputStream This is used to write to a file.
• OutputStream This is an abstract class that describe stream output.

CharacterStream:
In Java, characters are stored using Unicode conventions (Refer this for details). Character stream
automatically allows us to read/write data character by character. Though it has many classes, the
FileReader and the FileWriter are the most popular ones. FileReader and FileWriter are character
streams used to read from the source and write to the destination respectively. Here is the list of various
CharacterStream Classes:

• BufferedReader It is used to handle buffered input stream.
• FileReader This is an input stream that reads from file.
• InputStreamReader This input stream is used to translate byte to character.
• OutputStreamReader This output stream is used to translate character to byte.
• Reader This is an abstract class that define character stream input.
• PrintWriter This contains the most used print() and println() method
• Writer This is an abstract class that define character stream output.
• BufferedWriter This is used to handle buffered output stream.
• FileWriter This is used to output stream that writes to file.

JAVA PROGRAMMING BY (

Created by Page 231 of 401


Java File Class
The File class of the java.io package is used to perform various operations on files and directories.

To use the File class, create an object of the class, and specify the filename or directory name:

Example -

import java.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

The File class has many useful methods for creating and getting information about files. For example:

Method Type Description
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory


File Operations

The following are the several operations that can be performed on a file in Java:

• Create a File
• Read from a File
• Write to a File
• Delete a File

1. Create a File
• In order to create a file in Java, we can use the createNewFile() method of File class.
• If the file is successfully created, it will return a Boolean value true and false if the file already
exists.

// Creating File using Java Program

// Import the File class

JAVA PROGRAMMING BY (

Created by Page 232 of 401

import java.io.File;
import java.io.IOException;

public class CreateFile
{
public static void main(String[] args)
{
// Creating the File also
// Handling Exception
try {
File Obj = new File("myfile.txt");

// Creating File
if (Obj.createNewFile())
{
System.out.println("File created: " + Obj.getName());
}
else
{
System.out.println("File already exists.");
}
}

// Exception Thrown
catch (IOException e)
{
System.out.println("An error has occurred.");

}
}
}

2. Reading from a file

• Reading bytes data from file using FileInputStream class

The FileInputStream class reads the data from a specific file (byte by byte). It is usually used to read
the contents of a file with raw bytes, such as images.

To read the contents of a file using this class −

First of all, we need to instantiate this class by passing a String variable or a File object, representing the
path of the file to be read.

JAVA PROGRAMMING BY (

Created by Page 233 of 401

Example-

FileInputStream fis = new FileInputStream("file_name");
or,
File file = new File("file_name");
FileInputStream fis = new FileInputStream(file);

read() method:

The read() method in Java's FileInputStream is used to read data (bytes) from a file. It has a few
variations:
• int read(): This reads a single byte of data from the input stream. It returns an integer representing
the byte value (0-255) or -1 if the end of the file has been reached.
• int read(byte[] b): This reads up to b.length bytes of data from the input stream into the byte array b.
It returns the number of bytes read, or -1 if the end of the file has been reached.
• int read(byte[] b, int off, int len): This reads up to len bytes of data from the input stream into the
byte array b, starting at offset off. It returns the number of bytes read, or -1 if the end of the file has
been reached.

Example of reading a file byte by byte using read():

import java.io.FileInputStream;
import java.io.IOException;

public class ReadFile
{
public static void main(String[] args)
{
FileInputStream fis=null;
try
{
fis = new FileInputStream("ReaddFile.java");
int data;
while ((data = fis.read()) != -1)
{
System.out.print((char) data);
}

}
catch (IOException e)
{
System.out.println("File Error...");
}
finally

JAVA PROGRAMMING BY (

Created by Page 234 of 401

{
try{
if (fis != null)
fis.close();
}
catch (IOException e)
{
System.out.println("File Error...");
}
}
}
}

• Reading character data from file using FileReader class

FileReader in Java is a class in the java.io package which can be used to read a stream of characters
from the files. Java IO FileReader class uses either specified charset or the platform’s default charset
for decoding from bytes to characters.

1. Charset: The Charset class is used to define methods for producing encoders and decoders and for
recovering several names combined with the charset.

2. Default Charset: The default charset is defined during implicit computer start-up and it depends on
the locale and charset of the underlying operating system.



Constructors of Java FileReader Class:

The Constructors inside FileReader are shown in the table below.

JAVA PROGRAMMING BY (

Created by Page 235 of 401

• FileReader(File file) : Creates a new FileReader with the the given File to read (using default
charset)
• FileReader(FileDescriptor fd) : Creates a new FileReader with given FileDescriptor to read
(using default charset)
• FileReader(File file, Charset charset): Creates a new FileReader with a given File to read (using
the given charset)
• FileReader(String filename): Creates a new FileReader with a a given FileName to read (using
default charset)
• FileReader(String filename, Charset charset): Creates a new FileReader with given File to read
(using the given charset)

Methods of Java FileReader Class:

The methods under FileReader are shown in the table below.

• read(): The read() method reads and passes a single character or -1 if the stream is ended.
• read(char[] charBuffer, int offset, int length): It reads a stream of characters and stores them in
the given Character Buffer. Offset is the position at which it starts reading and Length is the
total number of characters to be read. It passes plenty of characters read or -1 if the stream is
ended.
• ready(): It tells whether the stream is ready to be read. A stream is said to be ready if its input
buffer is not blank or empty.
• getEncoding(): The getEncoding() is used to return the title of the character encoding which is
being used by the stream.
• close(): It closes the stream and releases the system resources associated with it.

Example: Reading file character by character
import java.io.*;

// Driver Class
class ReadFile3 {
// main function
public static void main(String[] args)
{
try {
// FileReader Class used
FileReader fr = new FileReader("File1.java");

System.out.println("Reading char by char : \n");
int i;

// Using read method
while ((i = fr.read()) != -1) {
System.out.print((char)i);

JAVA PROGRAMMING BY (

Created by Page 236 of 401

}

// Close method called
fr.close();
System.out.println("FileReader closed!");
}
catch (Exception e) {
System.out.println(e);
}
}
}


Example: Reading file using character array

import java.io.*;

// Driver Class
class ReadFile4 {
// main function
public static void main(String[] args)
{
try {
// FileReader Class used
FileReader fr = new FileReader("File1.java");

System.out.println("Reading using array : \n");
char[] arr = new char[1000];

// Using read method for to get character array
fr.read(arr);
System.out.print(arr);

// Close method called
fr.close();
System.out.println("FileReader closed!");
}
catch (Exception e) {
System.out.println(e);
}
}
}

2. Write to a File

JAVA PROGRAMMING BY (

Created by Page 237 of 401


• Writing bytes data to file using FileOutputStream class

This writes data into a specific file or, file descriptor (byte by byte). It is usually used to write the
contents of a file with raw bytes, such as images.
To write the contents of a file using this class −
• First of all, we need to instantiate this class by passing a String variable or a File object,
representing the path of the file to be read.

FileOutputStream outputStream = new FileOutputStream("file_path");
or,
File file = new File("file_path");
FileOutputStream outputStream = new FileOutputStream (file);

Then write the data to a specified file using either of the variants of write() method –

• int write(int b) − This method accepts a single byte and writes it to the current OutputStream.
• int write(byte[] b) − This method accepts a byte array as parameter and writes data from it to
the current OutputStream.
• int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its
length (int) as parameters and writes its contents to the current OutputStream.

Example:
// Java Program to save data using FileOutputStream
import java.io.*;

class WriteFile {
public static void main(String[] args)
{
String data = "Writing file using FileOutputStream class";

try (FileOutputStream fos = new FileOutputStream("output.txt")) {

// Convert the string into bytes
byte[] dataBytes = data.getBytes();

// Write the bytes to the file
fos.write(dataBytes);

System.out.println("Data successfully written to the file.");
}
catch (IOException e) {
System.out.println("An error occurred...")
}

JAVA PROGRAMMING BY (

Created by Page 238 of 401

}
}

• Writing character data to file using FileWriter class

Java FileWriter class of the java.io package is used to write data in character form to a file. The
FileWriter class in Java is used to write character-oriented data to a file. It is a character-oriented class
that is used for file handling in Java.
• This Class inherits from OutputStreamWriter class which in turn inherits from the Writer class.
• The Constructors of this class assume that the default character encoding and the default byte-
buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter
on a FileOutputStream.
• FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider
using a FileOutputStream.
• FileWriter creates the output file if it is not present already.



Constructors of FileWriter Class

FileWriter(File file): It constructs a FileWriter object given a File object. It throws an IOException if
the file exists but is a directory rather than a regular file does not exist but cannot be created, or cannot
be opened for any other reason.

FileWriter(File file, boolean append): It constructs a FileWriter object given a File object. If the
second argument is true, then bytes will be written to the end of the file rather than the beginning. It
throws an IOException if the file exists but is a directory rather than a regular file or does not exist but
cannot be created, or cannot be opened for any other reason.

FileWriter(File file, Charset charset): It constructs the fileWriter when file and charset is given.

JAVA PROGRAMMING BY (

Created by Page 239 of 401

FileWriter(File file, Charset charset, boolean append): It constructs the fileWriter when file and
charset is given and a boolean indicating whether to append the data written or not.

FileWriter(String fileName): It constructs a FileWriter object given a file name.

FileWriter(String fileName, Boolean append): It constructs a FileWriter object given a file name
with a Boolean indicating whether or not to append the data written.

FileWriter(String fileName, Charset charset): It constructs a FileWriter when a fileName and
charset is given.

Methods of FileWriter Class

Method

Description

void write(int a) Writes a single character specified by an Integer value.
void write(String text) Write the string into FileWriter.
void write(char c) Write the char into FileWriter.
void write(char[] c) Write a char array into FileWriter.
void write(String str, int pos,
int length)
Writes a portion of the string from position pos until
the length number of characters.
void write(char ch[], int pos,
int length)
Writes the position of characters from array ch[] from
position pos till length number of characters.
void flush() Flushes the data of FileWriter.
void close() Close the FileWriter.
int getEncoding() Returns the character encoding used by FileWriter.


Exmaple: Writing Files using FileWriter class

// Import the FileWriter class

JAVA PROGRAMMING BY (

Created by Page 240 of 401

import java.io.FileWriter;
import java.io.IOException;

public class WriteFile2
{
public static void main(String[] args)
{
// Writing Text File
// Exception Handling
try {

FileWriter fw = new FileWriter("myfile.txt");

// Writing File
fw.write("Writing text to file using FileWriter class !!");
fw.close();

System.out.println("File Successfully written.");
}

// Exception Thrown
catch (IOException e) {
System.out.println("An error has occurred.");

}
}
}


// Program for Appending Data to a File
import java.io.*;

class AppendingFile
{
public static void main (String[] args)
{
// Appending Data in the File
try (FileWriter writer = new FileWriter(fileName, true)) {

// true for append mode
writer.write("\nAppending this line to the file.");
System.out.println("Data appended to the file successfully.");
}
catch (IOException e) {

JAVA PROGRAMMING BY (

Created by Page 241 of 401

System.out.println("An error occurred while appending"
+ " to the file: " + e.getMessage());
}
}
}


// Program to Copy a file to another file charater by character

import java.io.*;
class FileCopy2
{
public static void main(String []args) throws IOException
{
FileReader in=new FileReader("notes.txt");
FileWriter out=new FileWriter("notes-copy.txt");
int i;
while((i=in.read())!=-1)
{
System.out.print((char)i);
out.write((char)i);
}
in.close();
out.close();
System.out.println("File copied...");

}
}




// Java Program illustrating the Byte Stream to copy contents of one file to another file.

import java.io.*;
public class FileCopy {
public static void main(
String[] args) throws IOException
{

FileInputStream fis = null;
FileOutputStream fos = null;

try {

JAVA PROGRAMMING BY (

Created by Page 242 of 401

fis = new FileInputStream("File1.java");
fos = new FileOutputStream("File2.java");

// Reading source file and writing
// content to target file byte by byte
int temp;
while ((temp = fis.read())!= -1)
fos.write((byte)temp);
}
finally {
if (fos != null)
fos.close();
if (fis != null)
fis.close();
}
}
}
Tags