logo

Java에서 파일을 여는 방법

Java에서 파일을 여는 방법은 다음과 같습니다.

  • 자바 데스크탑 클래스
  • 자바 FileInputStream 클래스
  • 자바 BufferedReader 클래스
  • 자바 FileReader 클래스
  • 자바 스캐너 클래스
  • 자바 니오 패키지

자바 데스크탑 클래스

Java Desktop 클래스는 열려 있는() 파일을 여는 방법. 그것은 a에 속한다 java.awt 패키지. 데스크톱 구현은 플랫폼에 따라 다르므로 운영 체제가 데스크톱을 지원하는지 확인해야 합니다. Desktop 클래스는 파일을 처리하기 위해 기본 데스크탑에 등록된 관련 애플리케이션을 찾습니다. 연결된 애플리케이션이 없거나 애플리케이션을 시작하는 데 실패하면 FileNotFoundException . 지정된 URI를 표시하기 위해 사용자 기본 브라우저를 실행합니다.

  • 선택적 메일 수신 URI를 사용하여 사용자 기본 메일 클라이언트를 시작합니다.
  • 등록된 애플리케이션을 실행하여 지정된 파일을 열거나 편집하거나 인쇄합니다.

그만큼 열려 있는() Desktop 클래스의 메서드는 관련 응용 프로그램을 실행하여 파일을 엽니다. 파일을 인수로 사용합니다. 메소드의 서명은 다음과 같습니다.

 public void open (File file) throws IOException 

이 메서드에서는 다음과 같은 예외가 발생합니다.

동적 배열 자바
    NullPointer예외:파일이 null인 경우.IllegalArgumentException:파일이 존재하지 않을 때 발생합니다.IO예외:해당 파일 형식과 연결된 응용 프로그램이 없으면 발생합니다.지원되지 않는 작업 실행:현재 플랫폼이 Desktop.Action.Open 작업을 지원하지 않는 경우.

 import java.awt.Desktop; import java.io.*; public class OpenFileExample1 { public static void main(String[] args) { try { //constructor of file class having file as argument File file = new File('C:\demo\demofile.txt'); if(!Desktop.isDesktopSupported())//check if Desktop is supported by Platform or not { System.out.println('not supported'); return; } Desktop desktop = Desktop.getDesktop(); if(file.exists()) //checks file exists or not desktop.open(file); //opens the specified file } catch(Exception e) { e.printStackTrace(); } } } 

위 프로그램을 실행하면 기본 텍스트 편집기에서 지정된 텍스트 파일이 열립니다. .docx, .pdf 및 .webp 파일을 열 수도 있습니다.

산출:

Java에서 파일을 여는 방법

자바 FileInputStream 클래스

자바 파일입력스트림 클래스는 파일을 열고 읽는 데 사용됩니다. FileInputStream 클래스의 생성자를 사용하여 파일을 열고 읽을 수 있습니다. 생성자의 서명은 다음과 같습니다.

 public FileInputStream(File file) throws FileNotFoundException 

파일을 인수로 받아들입니다. 그것은 던진다 FileNotFoundException 파일이 존재하지 않거나 파일 이름이 디렉터리인 경우.

데이터 구조

 import java.io.*; import java.util.Scanner; public class OpenFileExample2 { public static void main(String args[]) { try { //constructor of file class having file as argument File file=new File('C:\demo\demofile.txt'); FileInputStream fis=new FileInputStream(file); //opens a connection to an actual file System.out.println('file content: '); int r=0; while((r=fis.read())!=-1) { System.out.print((char)r); //prints the content of the file } } catch(Exception e) { e.printStackTrace(); } } } 

산출:

Java에서 파일을 여는 방법

자바 BufferedReader 클래스

자바 버퍼링된 리더 클래스는 문자 입력 스트림에서 텍스트를 읽습니다. 그것은 a에 속한다 java.io 패키지. BufferedReader 클래스의 생성자를 사용하여 파일을 열거나 읽습니다. 생성자의 서명은 다음과 같습니다.

 public BufferedReader(Reader in) 

기본 크기의 입력 버퍼를 사용하는 버퍼링 문자 입력 스트림을 생성합니다. 기본 크기 입력 버퍼를 사용합니다.

 import java.io.*; import java.util.Scanner; public class OpenFileExample3 { public static void main(String args[]) { try { //constructor of File class having file as argument File file=new File('C:\demo\demofile.txt'); //creates a buffer reader input stream BufferedReader br=new BufferedReader(new FileReader(file)); System.out.println('file content: '); int r=0; while((r=br.read())!=-1) { System.out.print((char)r); } } catch(Exception e) { e.printStackTrace(); } } } 

산출:

Java에서 파일을 여는 방법

자바 FileReader 클래스

자바 파일리더 클래스는 파일을 열고 읽는 데에도 사용됩니다. 그것은 a에 속한다 java.io 패키지. 파일의 문자를 읽는 것이 편리합니다. FileInputStream 클래스를 사용하여 원시 바이트를 읽는 데 사용됩니다. FileInputStream 클래스의 생성자를 사용하여 파일을 열고 읽습니다. 생성자의 서명은 다음과 같습니다.

 public FileReader(File file) throws FileNotFoundException 

파일을 인수로 받아들입니다. 그것은 던진다 FileNotFoundException 지정된 파일이 존재하지 않거나 파일 이름이 디렉터리인 경우.

배열의 C 문자열

 import java.io.*; public class OpenFileExample4 { public static void main(String args[]) { try { //constructor of the File class having file as an argument FileReader fr=new FileReader('C:\demo\demofile.txt'); System.out.println('file content: '); int r=0; while((r=fr.read())!=-1) { System.out.print((char)r); //prints the content of the file } } catch(Exception e) { e.printStackTrace(); } } } 

산출:

Java에서 파일을 여는 방법

자바 스캐너 클래스

자바 스캐너 클래스는 파일을 열고 읽는 데에도 사용됩니다. Scanner 클래스는 다음에 속합니다. java.util 패키지. Scanner 클래스의 생성자는 파일을 열고 읽는 데 사용됩니다. 생성자의 서명은 다음과 같습니다.

자바 형식 문자열
 public scanner (File source) throws FileNotFoundException 

(스캔할) 파일을 인수로 받아들입니다. 그것도 던진다 FileNotFoundException , 파일 소스를 찾을 수 없는 경우.

 import java.io.File; import java.util.Scanner; public class OpenFileExample5 { public static void main(String[] args) { try { File file=new File('C:\demo\demofile.txt'); Scanner sc = new Scanner(file); //file to be scanned while (sc.hasNextLine()) //returns true if and only if scanner has another token System.out.println(sc.nextLine()); } catch(Exception e) { e.printStackTrace(); } } } 

산출:

Java에서 파일을 여는 방법

자바 니오 패키지

readAllLines() 메서드 : readAllLines() 메소드는 File 클래스의 메소드입니다. 파일의 모든 줄을 읽고 파일의 바이트가 UTF-8 문자 집합을 사용하여 문자로 디코딩됩니다. 파일의 행을 목록으로 반환합니다. 메소드의 서명은 다음과 같습니다.

 public static List readAllLines(Path path) throws IOException 

여기서 path는 파일 경로입니다.

위의 방법은 다음을 호출하는 것과 동일합니다.

 File.readAllLines(path, Standard CharSets.UTF_8) 

컬렉션.빈목록(): emptyList() 메소드는 java.util 패키지에 속하는 Collection 클래스의 메소드입니다. 빈 목록을 얻는 데 사용됩니다. 메소드의 서명은 다음과 같습니다.

 public static final List emptyList() 

 import java.util.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.io.*; public class OpenFileExample6 { public static List readFileInList(String fileName) { List lines = Collections.emptyList(); try { lines=Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return lines; } public static void main(String[] args) { List l = readFileInList('C:\demo\demofile.txt'); Iterator itr = l.iterator(); //access the elements while (itr.hasNext()) //returns true if and only if scanner has another token System.out.println(itr.next()); //prints the content of the file } } 

산출:

Java에서 파일을 여는 방법