How to Open a File With Java?

This lesson will teach you how to open and read files using Java programs. This skill is useful, as it allows us to store data in text format outside of our program. The file will be opened in our system when we run the program.

What Is a JAVA File?

Post On:Open a File With Java
Post Type:Java Tutorials
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:SoftwareTestingo Telegram Group

If you have a file with the JAVA extension, it is a Java source code file written in the Java programming language. This type of file is essential to the process of building Java applications. Because it is a plain text file, it can be opened and read in any text editor. Your computer will unlikely have a program installed that will open a JAVA file when double-clicked. If not, you can use one of the programs below by opening the software and then using a File or Import menu to browse for the file.

You must use a Java compiler to compile a Java file into a class file. The resulting class file will be in binary form and not human-readable. If your source code file contains multiple classes, each will be compiled into a separate class file.

How to Open JAVA Files?

Your computer will unlikely have a program installed that will open a JAVA file when double-clicked. If not, you can use one of the programs below by opening the software and then using a File or Import menu to browse for the file.

Any text editor, including Notepad in Windows and TextEdit in macOS, can read the text within a JAVA file.

There are several ways to open a file with Java. Some of these methods include:

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

Desktop Class in Java

We can open a file in Java using the Desktop class present in java.awt package. This class has an open () method that will do this for us. Remember that since the Desktop is platform-independent, we need to check if our Operating System supports it before trying to use it.

package com.SoftwareTestingO.IO;
import java.awt.Desktop;
import java.io.File;
public class OpenFile 
{
	public static void main(String[] args) 
	{
		try
        {
			//constructor of file class having file as argument  
			File file = new File("E:\\demo.txt");
            
			//check if Desktop is supported by Platform or not  
			if(!Desktop.isDesktopSupported())
            {
                System.out.println("not supported");
                return;
            }
            Desktop desktop = Desktop.getDesktop();
            
          //checks file exists or not 
            if(file.exists())
                desktop.open(file); //opens the specified file  
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

	}
}

Using the Java FileInputStream class

The FileInputStream class can be used to open a file in Java. There is a constructor for this class that opens the file.

package com.SoftwareTestingO.IO;
import java.io.File;
import java.io.FileInputStream;
public class OpenFile1 
{
	public static void main(String[] args) 
	{
		try
		{
			//constructor of file class having file as argument  
			File file = new File("E:\\demo.txt");

			//opens a connection to an actual file
			FileInputStream fis=new FileInputStream(file);       
			System.out.println("file content: ");  
			int r=0;  
			while((r=fis.read())!=-1)  
			{  
				//prints the content of the file
				System.out.print((char)r);        
			}  
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}

	}
}

Using Java BufferedReader class

The Java BufferedReader class can read text from a character input stream. It belongs to the java.io package, and we use its constructor to open or read a file. This creates a buffering character-input stream that uses a default-sized input buffer.

package com.SoftwareTestingO.IO;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class OpenFile 
{
	public static void main(String[] args) 
	{
		try
		{
			//constructor of file class having file as argument  
			File file = new File("E:\\demo.txt");

			//creates a buffer reader input stream  
			BufferedReader br = new BufferedReader(new FileReader(file));
			System.out.println("The file content is: ");
			int r = 0;
			while ((r = br.read()) != -1) 
			{
				System.out.print((char) r);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}

Using the Java FileReader class

The Java FileReader class can be used to open and read a file. It is part of the java.io package, which contains various convenience classes for reading characters from files. To read raw bytes from a file, you can use the FileInputStream class. The constructor of the FileInputStream class accepts a file name as an argument, which it uses to open and read the contents of the specified file.

package com.SoftwareTestingO.IO;
import java.io.FileReader;
public class OpenFile3 
{
	public static void main(String[] args) 
	{
		try
		{
			//constructor of the File class having file as an argument  
			FileReader fr = new FileReader("E:\\demo.txt");
			System.out.println("The file content is: ");
			int r = 0;
			while ((r = fr.read()) != -1) 
			{
				//prints the content of the file 
				System.out.print((char) r);   
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}

Using Scanner class

If you want to learn how to read and open a file in Java, use the Scanner class of java.util package can be helpful. The scanner class can parse text using regular expressions, breaking the input into smaller pieces based on a certain pattern.

The delimiter is whitespace by default, but you can add your own custom delimiter. To use the Scanner class for opening and reading a file, you’ll need to use its constructor.

package com.SoftwareTestingO.IO;
import java.io.File;
import java.util.Scanner;
public class OpenFile3 
{
	public static void main(String[] args) 
	{
		try
		{
			File file = new File("E:\\demo.txt");

			//file to be scanned 
			Scanner sc = new Scanner(file); 
			System.out.println("The file content is:");
			while (sc.hasNextLine())
				//returns true if and only if scanner has another token  
				System.out.println(sc.nextLine());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}

Using the Java NIO package

If you want to learn to read and open files in Java, the Java nio package has many classes and methods to help you. For this, there are two important methods are there:

  • readAllLines() method
  • Collections.emptyList()

readAllLines() method

The File class readAllLines() method reads all lines from a file and decodes bytes into characters using the UTF-8 charset. The readAllLines() method returns file lines as a list.

Collections.emptyList() method

The emptyList() method is a method of the Collection class, which belongs to java.util package. It is used to create an empty list.

package com.SoftwareTestingO.IO;
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 OpenFile5 
{
	public static List< String > readFileInList(String fileName) 
	{
		List < String > lines = Collections.emptyList();
		try 
		{
			lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
		}
		catch(IOException e) 
		{
			e.printStackTrace();
		}
		return lines;
	}
	public static void main(String[] args) 
	{
		System.out.println("File content:");
		List l = readFileInList("E:\\demo.txt");

		//access the elements  
		Iterator< String > itr = l.iterator(); 

		//returns true if and only if scanner has another token
		while (itr.hasNext())   

			//prints the content of the file
			System.out.println(itr.next());   
	}
}

Conclusion:

In this post, we have gone through the possible ways to Open a File With Java. But still, if you find any difficulties understanding the concept, you can ask us in the comment section, and we will be happy to help you.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment