Java Open File
Let’s have a look at the simple java open file program. If we try to open a file that doesn’t exist, it will throw java.lang.IllegalArgumentException
.
Let’s see Desktop class example for java open file.
JavaOpenFile.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.journaldev.files; import java.awt.Desktop; import java.io.File; import java.io.IOException; public class JavaOpenFile { public static void main(String[] args) throws IOException { //text file, should be opening in default text editor File file = new File("/Users/pankaj/source.txt"); //first check if Desktop is supported by Platform or not if(!Desktop.isDesktopSupported()){ System.out.println("Desktop is not supported"); return; } Desktop desktop = Desktop.getDesktop(); if(file.exists()) desktop.open(file); //let's try to open PDF file file = new File("/Users/pankaj/java.pdf"); if(file.exists()) desktop.open(file); } } |
When you run the above program, the text file will be opened in the default text editor. Similarly, a PDF file will be opened in adobe acrobat reader.
If there are no application associated with given file type or the application is failed to launch, open
method throws java.io.IOException
.
That’s all for a simple program to open a file in java.