In this tutorial we will see how to open our local files like pdf,doc,text e.t.c ..by using our java application. For that we have a class that is Desktop. This class is available in java.awt.Desktop package,The Desktop class allows a Java application to launch associated applications registered
on the native desktop to handle a URI or a file.
This class supports following operations:-
1)launching the user-default browser to show a specified URI;
2)launching the user-default mail client with an optional mailto URI;
3)launching a registered application to open, edit or print a specified file.
This class contains soo many methods. Now we will see the description of the methods which are we are going to use open the our local system files. In the following example we used isDesktopSupported() method it tests whether this class is supported on the current platform or not. AndgetDesktop() method is used to get the Desktop instance of the current browser context, open() method is used to Launches the associated application to open the file.
Let's see the example for better understanding and run this program in your local machines..
if you get any problem leave comment below. After the execution of the program it automatically
opens the specified file .
opens the specified file .
- package com.system;
- import java.awt.Desktop;
- import java.io.File;
- public class Test {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- try {
- File file = new File("D:\\Head First PHP & MySQL.pdf");
- if (file.exists()) {
- if (Desktop.isDesktopSupported()) {
- Desktop.getDesktop().open(file);
- } else {
- System.out.println("Awt Desktop is not supported!");
- }
- } else {
- System.out.println("File is not exists!");
- }
- System.out.println("Done");
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }


0 comments:
Post a Comment