File Handling in Java - GeeksforGeeks

03 Jan, 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 Classimport 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.
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 :
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:
AudioInputStreamByteArrayInputStreamFileInputStreamFilterInputStreamStringBufferInputStreamObjectInputStream
AudioInputStream
ByteArrayInputStream
FileInputStream
FilterInputStream
StringBufferInputStream
ObjectInputStream
// 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.
The output stream is used to write data to numerous output devices like the monitor, file, etc. OutputStream is an abstract superclass that represents an 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:
ByteArrayOutputStreamFileOutputStreamStringBufferOutputStreamObjectOutputStreamDataOutputStreamPrintStream
ByteArrayOutputStream
FileOutputStream
StringBufferOutputStream
ObjectOutputStream
DataOutputStream
PrintStream
// 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.
Based on the data type, there are two types of streams :
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.
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.
The following table depicts several File Class methods:
Let us now get acquainted with the various 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
// Import the File classimport java.io.File;  // Import the IOException class to handle errorsimport 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 classimport java.io.File;  // Import this class for handling errorsimport java.io.FileNotFoundException;   // Import the Scanner class to read content from text filesimport java.util.Scanner;   public class GFG {    public static void main(String[] args)    {        try {            File Obj = new File("myfile.txt");            Scanner Reader = new Scanner(Obj);            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 classimport java.io.FileWriter;   // Import the IOException class for handling errorsimport 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();        }    }}
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 classimport 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 : "                               + myObj.getName());        }        else {            System.out.println(                "Failed in deleting the file.");        }    }}
Output
Failed in deleting the file.
java-file-handling
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java