有时我们必须在 Java 程序中打开一个文件. java.awt.Desktop
可以用来打开一个文件在 Java. 桌面实现是基于平台的,所以首先,我们应该检查操作系统是否支持桌面。
Java 開啟檔案
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
1package com.journaldev.files;
2
3import java.awt.Desktop;
4import java.io.File;
5import java.io.IOException;
6
7public class JavaOpenFile {
8
9 public static void main(String[] args) throws IOException {
10 //text file, should be opening in default text editor
11 File file = new File("/Users/pankaj/source.txt");
12
13 //first check if Desktop is supported by Platform or not
14 if(!Desktop.isDesktopSupported()){
15 System.out.println("Desktop is not supported");
16 return;
17 }
18
19 Desktop desktop = Desktop.getDesktop();
20 if(file.exists()) desktop.open(file);
21
22 //let's try to open PDF file
23 file = new File("/Users/pankaj/java.pdf");
24 if(file.exists()) desktop.open(file);
25 }
26
27}
当您运行上述程序时,文本文件将在默认文本编辑器中打开。类似地,在 Adobe Acrobat Reader 中将打开 PDF 文件. 如果没有与该文件类型相关的应用程序,或者应用程序未能启动,则打开
方法会抛出java.io.IOException
。