0% found this document useful (0 votes)
31 views

File Handling in Java

File handling in java notes

Uploaded by

v9pzzqpg9m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

File Handling in Java

File handling in java notes

Uploaded by

v9pzzqpg9m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

CoursesTutorialsJavaPracticeContests

Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithreading Java Exceptio

File Handling in Java


Last Updated : 16 Nov, 2022
In Java, with the help of File Class, we can work with files. This File Class is
inside the java.io package. The File class can be used by creating an object of
the class and then specifying the name of the file.

Why File Handling is Required?

File Handling is an integral part of any programming language as file


handling enables us to store the output of any particular program in a file
and allows us to perform certain operations on it.
In simple words, file handling means reading and writing data to a file.

Java

// Importing File Class


import java.io.File;

class GFG {
public static void main(String[] args)
{

// File name specified


File obj = new File("myfile.txt");
System.out.println("File Created!");
}
}

Output

File Created!

In Java, the concept Stream is used in order to perform I/O operations on a


file. So at first, let us get acquainted with a concept known as Stream in Java.
We use cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Got It !
Policy

https://www.geeksforgeeks.org/file-handling-in-java/ 1/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

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.
There are two types of streams :

1. Input Stream:
The Java InputStream class is the superclass of all input streams. The input
stream is used to read data from numerous input devices like the keyboard,
network, etc. InputStream is an abstract class, and because of this, it is not
useful by itself. However, its subclasses are used to read data.

There are several subclasses of the InputStream class, which are as follows:

1. AudioInputStream
2. ByteArrayInputStream
3. FileInputStream
4. FilterInputStream
5. StringBufferInputStream
6. ObjectInputStream

We use cookies toan


Creating ensure you have the best browsing experience on our website. By using
InputStream
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/file-handling-in-java/ 2/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

// Creating an InputStream
InputStream obj = new FileInputStream();

Here, an input stream is created using FileInputStream.

Note: We can create an input stream from other subclasses as well as


InputStream.

Methods of InputStream

S Method Description
No.

1 read() Reads one byte of data from the input stream.

read(byte[] array) Reads byte from the stream and stores that byte in
2
() the specified array.

It marks the position in the input stream until the


3 mark()
data has been read.

Returns the number of bytes available in the input


4 available()
stream.

It checks if the mark() method and the reset()


5 markSupported()
method is supported in the stream.

Returns the control to the point where the mark


6 reset()
was set inside the stream.

Skips and removes a particular number of bytes


7 skips()
from the input stream.

8 close() Closes the input stream.

2. Output Stream:
We use cookies to ensure you have the best browsing experience on our website. By using
The
our site, yououtput stream
acknowledge ishave
that you usedreadtoand
write dataour
understood toCookie
numerous output devices like the
Policy & Privacy
monitor, file, etc. OutputStream Policy is an abstract superclass that represents an

https://www.geeksforgeeks.org/file-handling-in-java/ 3/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

output stream. OutputStream is an abstract class and because of this, it is


not useful by itself. However, its subclasses are used to write data.

There are several subclasses of the OutputStream class which are as


follows:

1. ByteArrayOutputStream
2. FileOutputStream
3. StringBufferOutputStream
4. ObjectOutputStream
5. DataOutputStream
6. PrintStream

Creating an OutputStream

// Creating an OutputStream
OutputStream obj = new FileOutputStream();

Here, an output stream is created using FileOutputStream.

Note: We can create an output stream from other subclasses as well


as OutputStream.

Methods of OutputStream

S. Method Description
No.

1. write() Writes the specified byte to the output stream.

write(byte[] Writes the bytes which are inside a specific array to


2.
array) the output stream.

3. close() Closes the output stream.

Forces to write all the data present in an output


4. flush()
stream to the destination.

We use cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge
Based that youtype,
on the data have read and understood
there are twoour Cookieof
types Policy & Privacy:
streams
Policy

https://www.geeksforgeeks.org/file-handling-in-java/ 4/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

1. Byte Stream:
This stream is used to read or write byte data. The byte stream is again
subdivided into two types which are as follows:

Byte Input Stream: Used to read byte data from different devices.
Byte Output Stream: Used to write byte data to different devices.

2. Character Stream:
This stream is used to read or write character data. Character stream is again
subdivided into 2 types which are as follows:

Character Input Stream: Used to read character data from different


devices.
Character Output Stream: Used to write character data to different
devices.

Owing to the fact that you know what a stream is, let’s polish up File
Handling in Java by further understanding the various methods that are
useful for performing operations on the files like creating, reading, and
writing files.

Java File Class Methods

The following table depicts several File Class methods:

Method Name Description Return


Type

It tests whether the file is readable or


canRead() Boolean
not.

It tests whether the file is writable or


canWrite() Boolean
not.

createNewFile() It creates an empty file. Boolean

delete() It deletes a file. Boolean

We use cookies toexists()


ensure you have the best browsing
It tests experience
whether theonfile
our website.
exists orBy not.
using Boolean
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/file-handling-in-java/ 5/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

Method Name Description Return


Type

length() Returns the size of the file in bytes. Long

getName() Returns the name of the file. String

Returns an array of the files in the


list() String[]
directory.

mkdir() Creates a new directory. Boolean

Returns the absolute pathname of the


getAbsolutePath() String
file.

Let us now get acquainted with the various file operations in Java.

File operations in Java

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

Now let us study each of the above operations in detail.

1. Create a File

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

Following is a demonstration of how to create a file in Java :

Java

We use//cookies
Import the File class
to ensure you have the best browsing experience on our website. By using
import java.io.File;
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy
// Import the IOException class to handle errors
https://www.geeksforgeeks.org/file-handling-in-java/ 6/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

import java.io.IOException;

public class GFG {


public static void main(String[] args)
{

try {
File Obj = new File("myfile.txt");
if (Obj.createNewFile()) {
System.out.println("File created: "
+ Obj.getName());
}
else {
System.out.println("File already exists.");
}
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}

Output

An error has occurred.

2. Read from a File: We will use the Scanner class in order to read contents
from a file. Following is a demonstration of how to read contents from a file
in Java :

Java

// Import the File class


import java.io.File;

// Import this class for handling errors


import java.io.FileNotFoundException;

// Import the Scanner class to read content from text files


import java.util.Scanner;

public class GFG {


public static void main(String[] args)
{
We use cookies to ensure
try {you have the best browsing experience on our website. By using
our site, you acknowledge that you
File Objhave
= read
newand understood our Cookie Policy & Privacy
File("myfile.txt");
Scanner Reader Policy= new Scanner(Obj);

https://www.geeksforgeeks.org/file-handling-in-java/ 7/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

while (Reader.hasNextLine()) {
String data = Reader.nextLine();
System.out.println(data);
}
Reader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}

Output

An error has occurred.

3. Write to a File: We use the FileWriter class along with its write() method
in order to write some text to the file. Following is a demonstration of how
to write text to a file in Java :

Java

// Import the FileWriter class


import java.io.FileWriter;

// Import the IOException class for handling errors


import java.io.IOException;

public class GFG {


public static void main(String[] args)
{
try {
FileWriter Writer
= new FileWriter("myfile.txt");
Writer.write(
"Files in Java are seriously good!!");
Writer.close();
System.out.println("Successfully written.");
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
We use cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/file-handling-in-java/ 8/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

Output

An error has occurred.

4. Delete a File: We use the delete() method in order to delete a file.


Following is a demonstration of how to delete a file in Java :

Java

// Import the File class


import java.io.File;

public class GFG {


public static void main(String[] args)
{
File Obj = new File("myfile.txt");
if (Obj.delete()) {
System.out.println("The deleted file is : "
+ Obj.getName());
}
else {
System.out.println(
"Failed in deleting the file.");
}
}
}

Output

Failed in deleting the file.

Feeling lost in the vast world of Backend Development? It's time for a
change! Join our Java Backend Development - Live Course and embark on an
exciting journey to master backend development efficiently and on schedule.
What We Offer:

Comprehensive Course
Expert Guidance for Efficient Learning
Hands-on Experience with Real-world Projects
Proven Track Record with 100,000+ Successful Geeks
We use cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/file-handling-in-java/ 9/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

78 Suggest improvement

Next

File Handling in LISP

Share your thoughts in the comments Add Your Comment

Similar Reads
File Handling in Java with CRUD Java File Handling Programs
operations

File handling in Java using FileWriter Spring Boot - File Handling


and FileReader

How to Execute SQL File with Java Different Ways to Copy Content From
using File and IO Streams? One File to Another File in Java

Java Program to Read Content From How to Convert a Kotlin Source File to a
One File and Write it into Another File Java Source File in Android?

How to Extract File Extension From a How to Create a File with a Specific File
File Path String in Java? Attribute in Java?

S shreyasna…

Article Tags : java-file-handling , Java


Practice Tags : Java

We use cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/file-handling-in-java/ 10/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

A-143, 9th Floor, Sovereign Corporate


Tower, Sector-136, Noida, Uttar Pradesh -
201305

Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Careers GfG Weekly Contest
In Media Offline Classes (Delhi/NCR)
Contact Us DSA in JAVA/C++
Advertise with us Master System Design
GFG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Geeks Community

Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL DSA Interview Questions
R Language Competitive Programming
Android Tutorial

Data Science & ML Web Technologies


Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning Tutorial JavaScript
ML Maths TypeScript
Data Visualisation Tutorial ReactJS
Pandas Tutorial NextJS
We use cookies to ensureNumPy Tutorial
you have the best browsing experience on our website. By using NodeJs
our site, you acknowledgeNLP
thatTutorial
you have read and understood our Cookie Policy & PrivacyBootstrap
Deep Learning TutorialPolicy Tailwind CSS

https://www.geeksforgeeks.org/file-handling-in-java/ 11/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks

Python Tutorial Computer Science


Python Programming Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths

DevOps System Design


Git High Level Design
AWS Low Level Design
Docker UML Diagrams
Kubernetes Interview Guide
Azure Design Patterns
GCP OOAD
DevOps Roadmap System Design Bootcamp
Interview Questions

School Subjects Commerce


Mathematics Accountancy
Physics Business Studies
Chemistry Economics
Biology Management
Social Science HR Management
English Grammar Finance
Income Tax

UPSC Study Material Preparation Corner


Polity Notes Company-Wise Recruitment Process
Geography Notes Resume Templates
History Notes Aptitude Preparation
Science and Technology Notes Puzzles
Economy Notes Company-Wise Preparation
Ethics Notes Companies
Previous Year Papers Colleges

Competitive Exams More Tutorials


JEE Advanced Software Development
UGC NET Software Testing
SSC CGL Product Management
SBI PO Project Management
SBI Clerk Linux
IBPS PO Excel
IBPS Clerk All Cheat Sheets

Free Online Tools Write & Earn


Typing Test Write an Article
Image Editor Improve an Article
We use cookies to ensure youFormatters
Code have the best browsing experience on our website. By using
Pick Topics to Write
our site, you acknowledge that you have
Code Converters read and understood our Cookie Policy & Privacy
Share your Experiences
Currency Converter
Policy Internships
https://www.geeksforgeeks.org/file-handling-in-java/ 12/13
12/05/2024, 22:33 File Handling in Java - GeeksforGeeks
Random Number Generator
Random Password Generator

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

We use cookies to ensure you have the best browsing experience on our website. By using
our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
Policy

https://www.geeksforgeeks.org/file-handling-in-java/ 13/13

You might also like