How to Open a File in Java?

Files are containers where we can store large amounts of data. Java has a separate class to deal with File operations like File creation, opening/reading, writing, updating, deleting, etc. Every programmer will face a situation where they have to do file manipulation. In this tutorial, we will learn how to open a file in java. Without any delays, let us begin the tutorial.

What is a File class in java?

We use two packages to perform file operations. They are

1. java.io package 

2. java.nio.package

Generally, the java io package provides all the classes needed for performing input and output operations. It is the most commonly used package for file handling. The java nio package is the newer version introduced in JDK4 to make the IO operations faster and at high speed. Java nio is a high-performance file-handling API.

The File class is a part of java.io.package.We must create an object to use the file operations provided by the File class. It is the fundamental step for file manipulation in java.

Syntax:

File object_name = new File(path/filename.txt);

Example:

File open_file = new File(“FirstCode.txt”);
Or
File open_file = new File(“E:\\FirstCode.txt”);

In this tutorial, we will learn how to open a file using both java.io.package and java.nio.package.

Ways to Open/Read a file in Java:

There are six ways available to open or read a file in java. They are:

1. Desktop class 

2. Scanner class

3. FileReader class

4. FileInputStream class

5. BufferedReader class

6. Java nio package

The first five ways use the java.io package, and the last way uses the java.nio package. Let us move on further to know more about it with examples.

Consider that we have a file named FirstCode stored in the following path.

E:\FirstCode

The file FirstCode is a text file, and it contains the following contents in it.

Welcome to FirstCode.
FirstCode is one of the best online training providers.
They provide tutorials on programming languages.

1. Java Desktop class:

The java Desktop class is a part of java.awt package. This class has an open() method to open the specified file. This method launches the default associated application to open the file. An associated application is a tool, software, or application that helps to open a file in your system. If there is no associated application or the application fails to get launched, it throws a FileNotFound Exception. 

This method is not suitable for everyone because it is platform-dependent. So it is necessary to check whether your system supports this feature. A minimum of Java 9 is required to use this feature.

Exceptions to be handled:

It is necessary to handle the following exception while using this Desktop class.

1. NullPointerException: This exception occurs when the file is null.

2. IOException: It occurs when the associated application is not available.

3. UnsupportedOperationExecution: This exception occurs when the platform does not support the Desktop class feature.

4. IllegalArgumentException: It occurs when the file does not exist.

Method Signature:

public void open(File file) throws IOException

Syntax to use open() method:

desktopClassObject.open(fileObject);

We pass the file object as an argument to the open() method.

We all know that we must use the try-catch block to handle an exception.

Consider the following flowchart and code.

syntax to use open() method

import java.awt.Desktop;
import java.io.File;

public class OpenFile {
public static void main(String[] args) {
    try {
        // Creating a file object.
        File fileObject = new File("E:\\FirstCode.txt");
        //Check for system support.
        /* When the system supports the Desktop feature, the isDesktopSupported() method returns true. Then the "!" operator inverses it into false, So it does not execute the if statement.
Similarly, When the system does not support the Desktop feature, the isDesktopSupported() method returns false. Then the "!" operator inverses it into true, So the if statement is executed and returned.*/

        if(!Desktop.isDesktopSupported()) {
            System.out.println("This system does not support Desktop feature");
            return;
        }
        //Creating a desktop object.
        Desktop desktop = Desktop.getDesktop();
        //Checking whether the given file exists or not.
        if(fileObject.exists())
            // opening the file.
            desktop.open(fileObject);
        else
            System.out.println("File does not exist");
    }
    catch(Exception exception) {
        exception.printStackTrace();
    }
    
}
}

The above code opens the specified file in the default text editor like notepad, Wordpad, etc.

Output:

Welcome to FirstCode.
FirstCode is one of the best online training providers.
They provide tutorials on programming languages.

2. Java Scanner Class:

We all know that the Scanner class is a part of java.util package, and we use it to get input from the users. In addition, we can also use it to open and read a file.

Exceptions to be handled:

Here FileNotFoundException will be thrown when the specified file is not available.

Syntax:

Scanner scanner_object = new Scanner(fileObject);

Here we pass the file as an argument.

Flowchart:

scanner class

Code:

import java.io.File;
import java.util.Scanner;

public class OpenFile {
public static void main(String[] args) {
    try {
        //Creating a file object.
        File fileObject = new File("E:\\FirstCode.txt");
        //creating a scanner object.
        Scanner scan = new Scanner(fileObject);
        System.out.println("File Content is:");
        //reading the file and printing it. This loop repeats till the last token/character is available.
        while(scan.hasNextLine()) 
            System.out.println(scan.nextLine());
    }
    catch(Exception exception) {
        exception.printStackTrace();
    }
    
}
}

Output:

File Content is:
Welcome to FirstCode.
FirstCode is one of the best online training providers.
They provide tutorials on programming languages.

3. Java FileReader class:

In the java.io package, there is a class called FileReader. It opens and reads raw bytes or streams of characters from the files. It extends the InputStreamReader class.

Exceptions to be handled:

Here FileNotFoundException will be thrown when the specified file is not available.

Syntax:

FileReader object_name = new FileReader(filepath/filename);
Or 
FileReader object_name = new FileReader(fileobject);

Flowchart:

filereader class

Code:

import java.io.File;
import java.io.FileReader;

public class OpenFile {
public static void main(String[] args) {
    try {
        //Creating a file object.
        File fileObject = new File("E:\\FirstCode.txt");
        //Creating an object for FileReader class.
        FileReader reader = new FileReader(fileObject);
        //Reading the file and printing it.
        System.out.println("File Content is:");
        int r=0;
        /*This loop repeats till the last character or till the end of the file. The reader.read() method reads the character in the file. The character has some value that is not equal to -1. The variable r stores the value. The loop executes when the condition becomes true. If there is no more character to read, the method returns -1. So, the condition becomes false, and the loop stops executing.*/
        while((r=reader.read())!=-1) {
            //Print each character from the file.
            System.out.print((char)r);
        }
    }
    catch(Exception exception) {
        exception.printStackTrace();
    }
    
}
}

Output:

File Content is:
Welcome to FirstCode.
FirstCode is one of the best online training providers.
They provide tutorials on programming languages.

4. Java FileInputStream class:

In the java.io package, there is a class called FileInputStream. First, it opens and reads a file in the form of bytes. Then, it extends the InputStream class.

Exceptions to be handled:

Here FileNotFoundException will be thrown when the specified file is not available.

Syntax:

FileInputStream objectName = new FileInputStream(fileObject);

Flowchart:

fileinputstream class

Code:

import java.io.File;
import java.io.FileInputStream;

public class OpenFile {
public static void main(String[] args) {
    try {
        //Creating a file object.
        File fileObject = new File("E:\\FirstCode.txt");
        //Creating an object for FileInputStream class.
        FileInputStream reader = new FileInputStream(fileObject);
        System.out.println("File Content is:");
        //reading the file and printing it.
        int r=0;
        /*This loop repeats till the last character or till the end of the file. The reader.read() method reads the character in the file. The character has some value that is not equal to -1. The variable r stores the value. The loop executes when the condition becomes true. If there is no more character to read, the method returns -1. So, the condition becomes false, and the loop stops executing.*/
        while((r=reader.read())!=-1)
        {
//Print each character from the file.
            System.out.print((char)r);
        }
    }
    catch(Exception exception) {
        exception.printStackTrace();
    }
    
}
}

Output:

File Content is:
Welcome to FirstCode.
FirstCode is one of the best online training providers.
They provide tutorials on programming languages.

5. Java BufferedReader class:

The BufferedReader class is a part of the java.io package. It uses a character input stream to read the file.

It extends the Reader class and reads a group of characters from the disk and stores it in the internal buffer. The BufferedReader reads the characters in the buffer individually. So the number of times accessing the disk is reduced. So it provides high performance. We use it along with other reader classes like FileReader or InputStreamReader etc.

Exceptions to be handled:

Here FileNotFoundException will be thrown when the specified file is not available.

Syntax:

BufferedReader objectName = new BufferedReader(new FileReader(file));
Or
FileReader readerObjectName = new FileReader(“filepath/filename”);
BufferedReader objectName = new BufferedReader(readerObjectName);

Flowchart:

bufferedreader class

Code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class OpenFile {
public static void main(String[] args) {
    try {
        //Creating a file object.
        File fileObject = new File("E:\\FirstCode.txt");
        //Creating an object for the BufferedReader class.
        BufferedReader reader = new BufferedReader(new FileReader(fileObject));
        //reading the file and printing it.
        System.out.println("File Content is:");
        int r=0;
        /*This loop repeats till the last character or till the end of the file. The reader.read() method reads the character in the file. The character has some value that is not equal to -1. The variable r stores the value. The loop executes when the condition becomes true. If there is no more character to read, the method returns -1. So, the condition becomes false, and the loop stops executing.*/
        while((r=reader.read())!=-1)
        {
//Print each character from the file.
            System.out.print((char)r);
        }
    }
    catch(Exception exception) {
        exception.printStackTrace();
    }
    
}
}

Output:

File Content is:
Welcome to FirstCode.
FirstCode is one of the best online training providers.
They provide tutorials on programming languages.

6. Java nio package:

The Java nio package consists of all the classes for file manipulation like reading, writing, etc. For example, the following are the two methods to read the file in the java nio package.

1. readAllLines() method

2. Collections.emptyList()

The readAllLines() method of the File class reads all the lines from the file as bytes. Then the bytes are converted or decoded into characters based on the UTF-8 charset. The return type of this method is a list. So it returns all the lines of the file as a list. To store the data, we use Collections.emptyList() method to create an empty list. This Collections.emptyList() method is a part of the java.util package.

Syntax:

List<Type> listName = Collections.emptyList();
listName=Files.readAllLines(Paths.get(fileName),StandardCharsets.UTF_8);

Flowchart:

java nio package

Code:

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class OpenFile {
    
    public static List<String> readFileInList(String fileName)   
    {   
    //Creating an empty list.
    List<String> lines = Collections.emptyList();   
    try  
    {   
    // Reading the lines in the file and storing them in a list.
    lines=Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);   
    }   
    catch (IOException e)   
    {   
    e.printStackTrace();   
    }   
    return lines;   
    }   
    public static void main(String[] args)   
    {   
    //Calling the readFilelnList method.
    List l = readFileInList("E:\\FirstCode.txt");   
    //using an iterator to access the lines stored in the list.
    Iterator<String> itr = l.iterator();  
     //returns true if it has another element available next.
    while (itr.hasNext())    
    //Prints the content of the file.
  	System.out.println(itr.next());      
    }   

}

Output:

File Content is:
Welcome to FirstCode.
FirstCode is one of the best online training providers.
They provide tutorials on programming languages.

Summary

This article helps you learn to open or read Java files. You can choose any one of the above methods based on your requirements. So no more waiting, Dive in and start your programming voyage.

Leave a Reply

Your email address will not be published. Required fields are marked *