logo

Java에서 텍스트 파일을 읽는 다양한 방법

Java에서 텍스트 파일을 쓰고 읽는 방법에는 여러 가지가 있습니다. 이는 많은 애플리케이션을 처리하는 동안 필요합니다. Java에서 일반 텍스트 파일을 읽는 방법에는 여러 가지가 있습니다. FileReader, BufferedReader 또는 Scanner를 사용하여 텍스트 파일을 읽을 수 있습니다. 모든 유틸리티는 특별한 것을 제공합니다. BufferedReader는 빠른 읽기를 위해 데이터 버퍼링을 제공하고 Scanner는 구문 분석 기능을 제공합니다.

행동 양식:



  1. 사용 BufferedReader 클래스
  2. 사용 스캐너 클래스
  3. 파일 리더 클래스 사용
  4. 목록에서 전체 파일 읽기
  5. 텍스트 파일을 문자열로 읽기

BufferReader와 Scanner를 모두 사용하여 Java에서 텍스트 파일을 한 줄씩 읽을 수도 있습니다. 그런 다음 Java SE 8에는 또 다른 Stream 클래스가 도입되었습니다. java.util.stream.Stream 이는 파일을 읽는 게으르고 효율적인 방법을 제공합니다.

팁 참고: 초보자도 코드를 더 잘 이해할 수 있도록 스트림 플러시/닫기, 예외 처리 등과 같은 좋은 코드 작성 관행을 피했습니다.

위의 각 방법에 대해 더 깊이 논의하고 가장 중요한 것은 깨끗한 Java 프로그램을 통해 구현하는 것입니다.



1. 텍스트 파일 읽기를 위한 BufferedReader 클래스

이 메서드는 문자 입력 스트림에서 텍스트를 읽습니다. 문자, 배열 및 줄을 효율적으로 읽기 위해 버퍼링을 수행합니다. 버퍼 크기를 지정하거나 기본 크기를 사용할 수 있습니다. 기본값은 대부분의 목적에 충분히 큽니다. 일반적으로 Reader에 대한 각 읽기 요청은 기본 문자 또는 바이트 스트림에 대한 해당 읽기 요청을 발생시킵니다. 따라서 다음과 같이 FileReaders 및 InputStreamReaders와 같이 read() 작업에 비용이 많이 들 수 있는 모든 Reader 주위에 BufferedReader를 래핑하는 것이 좋습니다.

통사론

BufferedReader in = new BufferedReader(Reader in, int size);>



자바


쉐타 티와리



// Java Program to illustrate Reading from FileReader> // using BufferedReader Class> // Importing input output classes> import> java.io.*;> // Main class> public> class> GFG {> >// main driver method> >public> static> void> main(String[] args)>throws> Exception> >{> >// File path is passed as parameter> >File file =>new> File(> >'C:UserspankajDesktop est.txt'>);> >// Note: Double backquote is to avoid compiler> >// interpret words> >// like est as (ie. as a escape sequence)> >// Creating an object of BufferedReader class> >BufferedReader br> >=>new> BufferedReader(>new> FileReader(file));> >// Declaring a string variable> >String st;> >// Condition holds true till> >// there is character in a string> >while> ((st = br.readLine()) !=>null>)> >// Print the string> >System.out.println(st);> >}> }>

>

>

산출

If you want to code refer to techcodeview.com>

2. 텍스트 파일을 읽기 위한 FileReader 클래스

문자 파일을 읽기 위한 편의 클래스입니다. 이 클래스의 생성자는 기본 문자 인코딩과 기본 바이트 버퍼 크기가 적절하다고 가정합니다.

이 클래스에 정의된 생성자는 다음과 같습니다.

    FileReader(파일 파일): FileReader(FileDescriptor fd)에서 읽을 파일을 지정하여 새 FileReader를 생성합니다. FileReader(String fileName)에서 읽을 FileDescriptor를 지정하여 새 FileReader를 생성합니다. 읽을 파일

자바




무엇이 PC를 빠르게 만드는가?

// Java Program to Illustrate reading from> // FileReader using FileReader class> // Importing input output classes> import> java.io.*;> // Main class> // ReadingFromFile> public> class> GFG {> >// Main driver method> >public> static> void> main(String[] args)>throws> Exception> >{> >// Passing the path to the file as a parameter> >FileReader fr =>new> FileReader(> >'C:UserspankajDesktop est.txt'>);> >// Declaring loop variable> >int> i;> >// Holds true till there is nothing to read> >while> ((i = fr.read()) != ->1>)> >// Print all the content of a file> >System.out.print((>char>)i);> >}> }>

>

>

산출

If you want to code refer to techcodeview.com>

삼. 텍스트 파일을 읽기 위한 스캐너 클래스

정규식을 사용하여 기본 유형과 문자열을 구문 분석할 수 있는 간단한 텍스트 스캐너입니다. Scanner는 기본적으로 공백과 일치하는 구분 기호 패턴을 사용하여 입력을 토큰으로 나눕니다. 결과 토큰은 다양한 next 메소드를 사용하여 다양한 유형의 값으로 변환될 수 있습니다.

예시 1: 루프를 사용하여

자바




// Java Program to illustrate> // reading from Text File> // using Scanner Class> import> java.io.File;> import> java.util.Scanner;> public> class> ReadFromFileUsingScanner {> >public> static> void> main(String[] args)>throws> Exception> >{> >// pass the path to the file as a parameter> >File file =>new> File(> >'C:UserspankajDesktop est.txt'>);> >Scanner sc =>new> Scanner(file);> >while> (sc.hasNextLine())> >System.out.println(sc.nextLine());> >}> }>

>

>

산출

If you want to code refer to techcodeview.com>

예시 2: 루프를 사용하지 않고

자바




// Java Program to illustrate reading from FileReader> // using Scanner Class reading entire File> // without using loop> import> java.io.File;> import> java.io.FileNotFoundException;> import> java.util.Scanner;> public> class> ReadingEntireFileWithoutLoop {> >public> static> void> main(String[] args)> >throws> FileNotFoundException> >{> >File file =>new> File(> >'C:UserspankajDesktop est.txt'>);> >Scanner sc =>new> Scanner(file);> >// we just need to use  as delimiter> >sc.useDelimiter(>''>);> >System.out.println(sc.next());> >}> }>

>

>

산출

mysql 목록 사용자
If you want to code refer to techcodeview.com>

4. 목록에서 전체 파일 읽기

파일의 모든 줄을 읽습니다. 이 방법을 사용하면 모든 바이트를 읽었거나 I/O 오류 또는 기타 런타임 예외가 발생했을 때 파일이 닫히게 됩니다. 파일의 바이트는 지정된 문자 세트를 사용하여 문자로 디코딩됩니다.

통사론:

public static List readAllLines(Path path,Charset cs)throws IOException>

이 방법은 다음을 줄 종결자로 인식합니다.

u000D followed by u000A, CARRIAGE RETURN followed by LINE FEED u000A, LINE FEED u000D, CARRIAGE RETURN>

자바




// Java program to illustrate reading data from file> // using nio.File> import> java.io.*;> import> java.nio.charset.StandardCharsets;> import> java.nio.file.*;> import> java.util.*;> public> class> ReadFileIntoList {> >public> static> List> >readFileInList(String fileName)> >{> >List lines = Collections.emptyList();> >try> {> >lines = Files.readAllLines(> >Paths.get(fileName),> >StandardCharsets.UTF_8);> >}> >catch> (IOException e) {> >// do something> >e.printStackTrace();> >}> >return> lines;> >}> >public> static> void> main(String[] args)> >{> >List l = readFileInList(> >'C:UserspankajDesktop est.java'>);> >Iterator itr = l.iterator();> >while> (itr.hasNext())> >System.out.println(itr.next());> >}> }>

>

>

산출

If you want to code refer to techcodeview.com>

5. 텍스트 파일을 문자열로 읽기

자바




// Java Program to illustrate> // reading from text file> // as string in Java> package> io;> import> java.nio.file.*;> ;> public> class> ReadTextAsString {> >public> static> String readFileAsString(String fileName)> >throws> Exception> >{> >String data =>''>;> >data =>new> String(> >Files.readAllBytes(Paths.get(fileName)));> >return> data;> >}> >public> static> void> main(String[] args)>throws> Exception> >{> >String data = readFileAsString(> >'C:UserspankajDesktop est.java'>);> >System.out.println(data);> >}> }>

mysql 삽입
>

>

산출

If you want to code refer to techcodeview.com>