java

How to open a file in Java

In this tutorial, we are going to see how to open a file in java. Sometimes you have to open a file in a Java program. The java.awt.Desktop class can be used to open a file in java. The implementation of the Desktop class depends on the platform, so we first need to check whether the operating system supports the Desktop class or not. This class searches for the associated application registered on the current platform to open a file.

Let’s look at a simple program in java. If we try to open a file that doesn’t exist, it will throw the exception java.lang.IllegalArgumentException.
 

 

Java Program to open a file:
import java.awt.Desktop;
import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {

        File file = new File("file.txt");
        
        //Check whether the system supports Desktop class or not
        if(!Desktop.isDesktopSupported()){
            System.out.println("Desktop is not supported");
            return;
        }
        
        Desktop d = Desktop.getDesktop();
        if(file.exists()) 
            d.open(file);
    }
}

When you run the above code, the text file will be opened in the default text editor.
 

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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