A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/file-handling-in-java/ below:

File Handling in Java - GeeksforGeeks

File Handling in Java

Last Updated : 23 Jul, 2025

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 to create an object of the class and then specifying the name of the file.

Why File Handling is Required?

Example:

Java
// Importing File Class
import java.io.File;

class Geeks 
{
    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.

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:

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
Creating an InputStream:

// 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.

Common Methods of InputStream:

Method Description 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. mark() It marks the position in the input stream until the data has been read. available() Returns the number of bytes available in the input stream. markSupported() It checks if the mark() method and the reset() method is supported in the stream. reset() Returns the control to the point where the mark was set inside the stream. skips()  Skips and removes a particular number of bytes from the input stream. close() Closes the input stream. 2. Output Stream

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:

  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.

Common Methods of OutputStream:

Method Description 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.

Based on the data type, there are two types of streams:

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:

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:

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 canRead()  It tests whether the file is readable or not.  Boolean canWrite() It tests whether the file is writable or not. Boolean createNewFile() It creates an empty file. Boolean delete() It deletes a file. Boolean exists() It tests whether the file exists or not. Boolean length() Returns the size of the file in bytes. Long getName()  Returns the name of the file. String list() Returns an array of the files in the directory. String[]  mkdir()  Creates a new directory. Boolean getAbsolutePath() Returns the absolute pathname of the file. String

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

File Operations

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

1. Create a File

Example:

Java
// Creating File using Java Program

// Import the File class
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.");
            e.printStackTrace();
        }
    }
}

Output:

2. Write to a File

We use the FileWriter class along with its write() method in order to write some text to the file.

Example:

Java
// Writing Files using Java Program

// Import the FileWriter class
import java.io.FileWriter;
import java.io.IOException; 

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

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

            // Writing File
            Writer.write("Files in Java are seriously good!!");
            Writer.close();
            
            System.out.println("Successfully written.");
        }

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

Output:

3. Read from a File

We will use the Scanner class in order to read contents from a file.

Example:

Java
// Reading File using Java Program

// Import the File class
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner; 

public class ReadFile 
{
    public static void main(String[] args)
    {
        // Reading File also
        // Handling Exception
        try {
            File Obj = new File("myfile.txt");
            Scanner Reader = new Scanner(Obj);
          
            // Traversing File Data
          	while (Reader.hasNextLine()) {
                String data = Reader.nextLine();
                System.out.println(data);
            }
          
            Reader.close();
        }
        
        // Exception Cases
        catch (FileNotFoundException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}

Output:

4. Delete a File

We use the delete() method in order to delete a file.

Example:

Java
// Deleting File using Java Program
import java.io.File; 

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

Output:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4