English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 예제에서는 Java에서 다양한 클래스를 사용하여 파일 내용을 읽는 방법을 배울 것입니다
이 예제를 이해하기 위해 다음 사항을 이해해야 합니다Java 프로그래밍주제:
import java.io.BufferedInputStream; import java.io.FileInputStream; class Main { public static void main(String[] args) { try { //FileInputStream을 생성합니다 FileInputStream file = new FileInputStream("input.txt"); //BufferedInputStream을 생성합니다 BufferedInputStream input = new BufferedInputStream(file); //파일에서 첫 번째 바이트를 읽습니다 int i = input.read(); while (i != -1) { System.out.print((char) i); // 파일에서 다음 바이트를 읽습니다 i = input.read(); } input.close(); } catch (Exception e) { e.getStackTrace(); } } }
출력 결과
First Line Second Line Third Line Fourth Line Fifth Line
위의 예제에서는 BufferedInputStreamClass에서 이름이input.txt의 파일에서 행별로 읽습니다.
주의이 파일을 실행하려면 현재 작업 디렉토리에 input.txt 파일이 있어야 합니다.
import java.io.FileReader; import java.io.BufferedReader; class Main { public static void main(String[] args) { //문자 배열을 생성합니다 char[] array = new char[100]; try { // FileReader를 생성합니다 FileReader file = new FileReader("input.txt"); //BufferedReader를 생성합니다 BufferedReader input = new BufferedReader(file); //문자를 읽습니다 input.read(array); System.out.println("파일의 데이터: "); System.out.println(array); //읽기기를 닫습니다 input.close(); } catch(Exception e) { e.getStackTrace(); } } }
출력 결과
파일의 데이터: First Line Second Line Third Line Fourth Line Fifth Line
위의 예제에서는 다음과 같이 사용했습니다:BufferedReader 클래스이름이input.txt의 파일.
import java.io.File; import java.util.Scanner; class Main { public static void main(String[] args) { try { //새 파일 객체를 생성합니다 File file = new File("input.txt"); //파일과 연결된 스캔러 객체를 생성합니다 Scanner sc = new Scanner(file); //파일의 각 행을 읽고 출력합니다 System.out.println("파일을 스캔러로 읽기:"); while(sc.hasNextLine()) { System.out.println(sc.nextLine()); } //스캐너를 닫기 sc.close(); } catch (Exception e) { e.getStackTrace(); } } }
출력 결과
스캐너를 사용하여 파일을 읽기: First Line Second Line Third Line Fourth Line Fifth Line
위의 예제에서는 file이라는 File 클래스의 객체를 생성했습니다. 그런 다음, 해당 파일과 연결된 Scanner 객체를 생성했습니다.
여기서는 스캐너 메서드를 사용했습니다
hasNextLine() - 파일에 다음 줄이 있으면 true를 반환
nextLine() - 파일에서 한 줄을 반환
스캐너에 대한更多信息를 알고 싶다면 방문해 주세요Java Scanner。