Open any external file using java
So if you are here it is sure you need a piece of code which could help you to open any external file using java.And this article will tell you how you could do that.
java.awt.Desktop
The Desktop class of awt package allows java programs to launch any file in its default editor.Means if the file is .txt it might open in Notepad if it is .pdf then it will open in adobe reader and if it is (.html) then it will open in your default web browser.
NOTE:- If we will try to open a file which does not exists then it will throw
java.lang.IllegalArgumentException
So here is the whole source code
openIt.java
import java.util.Scanner;
public class OpeIt {
public static void main(String[] args) throws IOException
{
System.out.print("Enter the path of the file to open");
String path=sc.nextLine();
File file = new File(path);
//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);
else
System.out.println("The file does not exists");
}
}
If there is no application associated with the given file type then the open method will
simply throws java.io.IOException
0 comments:
Post a Comment