Java에서 파일을 여는 방법
때때로 우리는 자바 프로그램에서 파일을 열어야 합니다. java.awt.Desktop
은 java에서 파일을 여는 데 사용할 수 있습니다. 데스크톱 구현은 플랫폼에 따라 다르므로 먼저 운영 체제가 데스크톱을 지원하는지 확인해야 합니다. 이 클래스는 파일을 열기 위해 현재 플랫폼에 등록된 관련 응용 프로그램을 찾습니다.
자바 파일 열기
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);
}
}
위의 프로그램을 실행하면 기본 텍스트 편집기에서 텍스트 파일이 열립니다. 마찬가지로 Adobe Acrobat Reader에서 PDF 파일이 열립니다. 지정된 파일 형식과 연결된 응용 프로그램이 없거나 응용 프로그램 실행에 실패한 경우 open
메서드는 java.io.IOException
을 발생시킵니다. 이것이 자바에서 파일을 여는 간단한 프로그램을 위한 전부입니다.