How to Open a File in Java?

Free Java courses with 37 real-time projects - Learn Java

We already know how to create a file in Java. Java also provides us with the provision to open and access the contents of a file. There are a total of six different ways in which we can open a file in Java. In this article, we will take a look at all those methods to open file in java.

Opening a file in Java:

There are a total of six different ways to open a file in Java using different classes like:

  • Desktop class
  • FileInputStream class
  • BufferedReader class
  • FileReader class
  • Scanner class
  • nio package

Let us discuss them one by one at length.

We have created a file with the name “NewTextFile”, in the location “G:\Internship\NewTextFile.txt”

The file contains the following data:
“This is a tutorial on how to open a file in Java
DataFlair”

So, we will now open this file using different techniques.

1. Open file using Java Desktop class:

The Java Desktop class contains an open() method that provides provision to open a file in Java. It is part of the java.awt package. Although Java is a platform-independent language, the Java Desktop class is platform-dependent. We need to check the system for Desktop support, before implementing this method. This class looks for an associated application on the Desktop of the system, to handle the file.

The class throws the FileNotFoundExeption, if there is no associated application or if the application fails to launch.

  • This class launches the user’s default browser to show a specific URL.
  • It launches the user’s default mail client with an optional mail to URL.
  • It launches the registered application to open, edit or print a file.

The open() method takes the file as an argument and launches the associated application to open the file.

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

The signature of the method is:

public void open (File file) throws IOException  

Exceptions thrown by the method:

  • If the file is null, it throws the NullPointerException.
  • If the file does not exist, it throws the IllegalArgumentException.
  • When there is no application associated with the given file type, it throws the IOException.
  • If the current platform does not support the Desktop.Action.Open action, it throws the UnsupportedOperationExecution.

Code to open a file using the Desktop Class:

package com.DataFlair.FileOpening;
import java.awt.Desktop;  
import java.io.*;  
public class DesktopClass
{
    public static void main(String[] args)   
        {  
        try  
            {  
            File file_open = new File("G:\\Internship\\NewTextFile.txt");   
            if(!Desktop.isDesktopSupported())
            {  
                System.out.println("Desktop Support Not Present in the system.");  
                return;  
            }  
            Desktop desktop = Desktop.getDesktop();  
            if(file_open.exists())         
                desktop.open(file_open);             
        }  
        catch(Exception e)  
        {  
            e.printStackTrace();  
        }  
        }  
}

The output of the above code:

desktop method

 

So, we can see that the file is opened in the Notepad application, which is the default application of the system to open a text file.

2. Open file using Java FileInputStream class:

The FileInputStream class present in the java.io package also helps in opening and reading a file. By using the constructor of this class we can read a file in Java.

The signature of the FileInputStream constructor is:

public FileInputStream(File file) throws FileNotFoundException  

This constructor takes a file as an argument. It throws FileNotFoundException if the file does not exist or if the file is a directory.

Code to understand the FileInputStream class:

package com.DataFlair.FileOpening;
import java.io.*;  
import java.util.Scanner;  
public class FileInputStreamClass
{
    public static void main(String args[])  
    {  
        try  
        {  
            File file_create=new File("G:\\Internship\\NewTextFile.txt");   
            FileInputStream fin=new FileInputStream(file_create);
            System.out.println("The content of the File are: ");  
            int ch=0;  
            while((ch=fin.read())!=-1)  
            {  
                System.out.print((char)ch); 
            }  
        }  
        catch(Exception e)  
        {  
            e.printStackTrace();  
        }  
    }  
}

The output of the above code:

The content of the File are:
This is a tutorial on how to open a file in Java
DataFlair

3. Open file using Java BufferedReader class:

The java BufferedReader class reads characters from the character input stream. It is part of the java.io package. We can use the constructor of this class to open and read a file.

The signature of the constructor is:

public BufferedReader(Reader in)  

The constructor throws the FileNotFoundException, if the file does not exist or is the name of a directory.

Code to understand the BufferedReader class:

package com.DataFlair.FileOpening;
import java.io.*;  
import java.util.Scanner;  
public class BufferedReaderClass
{
    public static void main(String args[])  
    {  
        try  
        {   
            File file_open=new File("G:\\Internship\\NewTextFile.txt");   
            BufferedReader br=new BufferedReader(new FileReader(file_open));  
            System.out.println("The content of the file are: ");  
            int ch=0;  
            while((ch=br.read())!=-1)  
            {  
            System.out.print((char)ch);  
            }  
        }  
        catch(Exception e)  
        {  
            e.printStackTrace();  
        }  
    }  
}

The output of the above code is:

The content of the file are:
This is a tutorial on how to open a file in Java
DataFlair

4. Open file using Java FileReader class:

The java FileReader class is also a part of the java.io package, and we can use it to read and open files as well. Using this class we can read the raw bytes of a file. We use the constructor of the FileReader class to open and read a file.

The signature of the constructor is:

public FileReader(File file) throws FileNotFoundException  

The constructor throws the FileNotFoundException, if the file does not exist or is the name of a directory.

Code to understand FileReader class:

package com.DataFlair.FileOpening;
import java.io.*;
public class FileReaderClass
{
    public static void main(String args[])  
    {  
        try  
        {   
            FileReader file_open=new FileReader("G:\\Internship\\NewTextFile.txt");   
            System.out.println("The contents of the file are: ");  
            int ch=0;  
            while((ch=file_open.read())!=-1)  
            {  
                System.out.print((char)ch);   
            }  
        }  
        catch(Exception e)  
        {  
            e.printStackTrace();  
        }  
    }  
}

The output of the above code:

The contents of the file are:
This is a tutorial on how to open a file in Java
DataFlair

5. Open file using Java Scanner class:

The Java Scanner class is part of the Java utility package(java.util). It is also used to open and read files. The constructor of the scanner class takes the file as input and reads the file. If the file does not exist or if it is the name of a directory, the constructor throws the FileNotFoundException.

The signature of the constructor is:

public scanner (File source) throws FileNotFoundException  

Code to understand the Scanner class:

package com.DataFlair.FileOpening;
import java.io.File;
import java.util.*;
public class ScannerClass
{
    public static void main(String[] args)   
    {   
        try  
        {  
            File file_open=new File("G:\\Internship\\NewTextFile.txt");   
            Scanner sc = new Scanner(file_open); 
            System.out.println("The contents of the file are: ");
            while (sc.hasNextLine())        
            System.out.println(sc.nextLine());    
        }  
        catch(Exception e)  
        {  
            e.printStackTrace();  
        }  
    }   
}

The output of the above code:

The contents of the file are:
This is a tutorial on how to open a file in Java
DataFlair

Code to open a file using Scanner class but without any loop:

package com.DataFlair.FileOpening;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop
{
  public static void main(String[] args)throws FileNotFoundException
  {
    File file = new File("G:\\Internship\\NewTextFile.txt");
    Scanner sc = new Scanner(file);
    sc.useDelimiter("\\A");//Using a custom character as a delimeter,in this case "\\A"
    System.out.println(sc.next());
  }
}

The output of the above code:

This is a tutorial on how to open a file in Java
DataFlair

6. Open file using the nio package:

The java.nio package contains a method readAllLines(), which reads all lines from a file and bytes from the file are decoded into characters using the UTF-8 charset. The method returns all the lines of the file as a list.

The signature of the method is:

public static List<String> readAllLines(Path path) throws IOException

Where path is the path of the File.

The above method can also be written in a simpler way as:

File.readAllLines(path, Standard CharSets.UTF_8)  

We will also need an empty list to store the data.

Collection.emptyList() is a method of the Collection class of java.util package. The method is used to obtain an empty list.

The signature of the method is:

public static final <T> List <T> emptyList()  

Code to understand the nio package and opening file in a List:

package com.DataFlair.FileOpening;
import java.util.*;   
import java.nio.charset.StandardCharsets;   
import java.nio.file.*;   
import java.io.*;   
public class nioPackage
{
    public static List<String> readFileInList(String file_Name)   
    {   
        List<String> lines = Collections.emptyList();   
        try  
        {   
            lines=Files.readAllLines(Paths.get(file_Name), StandardCharsets.UTF_8);   
        }   
        catch (IOException e)   
        {   
            e.printStackTrace();   
        }   
        return lines;   
    }   
    public static void main(String[] args)   
    {   
        List list = readFileInList("G:\\internship\\NewTextFile.txt");   
        Iterator<String> iter = list.iterator();   
        System.out.println("The contents of the file are: ");
        while (iter.hasNext())       
        System.out.println(iter.next());       
    }   
}  

The output of the above code:

The contents of the file are:
This is a tutorial on how to open a file in Java
DataFlair

Code to understand the nio package and opening file in a String:

package com.DataFlair.FileOpening;
import java.nio.file.*;
public class nioPackageString
{
  public static String openFileAsString(String fName)throws Exception
  {
    String contents = "";
    contents = new String(Files.readAllBytes(Paths.get(fName)));
    return contents;
  }
  public static void main(String[] args) throws Exception
  {
    String data = openFileAsString("G://Internship//NewTextFile.txt");
    System.out.println(data);
  }
}

The output of the above code:

This is a tutorial on how to open a file in Java
DataFlair

Conclusion:

As we can see, there are many ways to read/open a file. It all depends on the programmer’s will, which method suits his purpose. In this article, we saw all the different ways in which we can open a file. We discussed each of these methods with proper examples and code.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

Leave a Reply

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