How to open a File in Java With Examples

Sometimes we have to open a file in java program. java.awt.Desktop can be used to open a file in java. Desktop implementation is platform dependent, so first, we should check if the operating system supports Desktop or not. This class looks for the associated application registered to the current platform to open a file.

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

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.

By admin

Leave a Reply