Java로 일반 텍스트 파일 읽기


933

Java로 파일의 데이터를 읽고 쓰는 다른 방법이있는 것 같습니다.

파일에서 ASCII 데이터를 읽고 싶습니다. 가능한 방법과 차이점은 무엇입니까?


24
또한 "건설적이지 않다"는 말에 동의하지 않습니다. 다행히도 이것은 복제 로 닫힐 수 있습니다 . 좋은 답변 예를 들어 파일의 내용에서 문자열을 만드는 방법? , 파일을 문자열로 읽는 가장 간단한 방법은 무엇입니까? , 파일을 읽는 가장 간단한 클래스는 무엇입니까?
Jonik

루프 없음 : {{{스캐너 sc = 새 스캐너 (파일, "UTF-8"); sc.useDelimiter ( "$ ^"); // 아무것도 일치하지 않는 정규 표현식 String text = sc.next (); sc.close (); }}}
Aivar

3
파이썬에서 "read ()"와 같은 것이 없다는 것은 흥미 롭다. 전체 파일을 문자열로 읽는다.
kommradHomer

2
이 작업을 수행하는 가장 간단한 방법은 다음과 같습니다. mkyong.com/java/…
dellasavia

답변:


567

ASCII는 텍스트 파일이므로 Readers읽을 때 사용 합니다. Java는 또한를 사용하여 이진 파일에서 읽기를 지원합니다 InputStreams. 읽고있는 파일이 너무 큰 경우 BufferedReader에는FileReader 읽기 성능을 향상 할 수 있습니다.

이 기사를 살펴보십시오 을 사용하는 방법에Reader

또한 Thinking In Java 라는이 훌륭한 (아직 무료) 책을 다운로드하여 읽는 것이 좋습니다 .

Java 7에서 :

new String(Files.readAllBytes(...))

(문서) 또는

Files.readAllLines(...)

(문서)

Java 8에서 :

Files.lines(..).forEach(...)

(문서)


14
리더 선택은 실제로 파일 내용에 필요한 내용에 따라 다릅니다. 파일이 작고 모두 필요한 경우 FileReader를 사용하고 모든 것을 읽거나 (또는 ​​최소한 큰 덩어리) 읽는 것이 더 빠릅니다 (우리는 1.8-2x로 표시). 한 줄씩 처리하는 경우 BufferedReader로 이동하십시오.
Vlad

3
"Files.lines (..). forEach (...)"를 사용할 때 줄 순서가 유지됩니까? 나는이 작업 후에 순서가 임의적이라는 것을 이해합니다.
Daniil Shevelev

39
Files.lines(…).forEach(…)줄의 순서는 유지하지 않지만 @Dash와 병렬로 실행됩니다. 순서가 중요한 경우 순서 Files.lines(…).forEachOrdered(…)를 유지해야하는를 사용할 수 있습니다 (확인하지는 않음).
Palec

2
@Palec 이것은 흥미 롭지 만 Files.lines(...).forEach(...)병렬로 실행 된다는 문서에서 인용 할 수 있습니까? 나는 이것을 명시 적으로 사용하여 스트림을 병렬로 만들 때만 그렇다고 생각했다 Files.lines(...).parallel().forEach(...).
Klitos Kyriacou 14시 03 분

3
내 원래 공식은 @KlitosKyriacou입니다. 요점은 forEach순서를 보장하지 않으며 그 이유는 병렬화가 쉽다는 것입니다. 순서를 유지하려면을 사용하십시오 forEachOrdered.
Palec

687

작은 파일을 읽는 가장 좋아하는 방법은 BufferedReader와 StringBuilder를 사용하는 것입니다. 그것은 매우 간단하고 요점입니다 (특히 효과적이지는 않지만 대부분의 경우 충분합니다).

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();
}

일부 사람들은 Java 7 이후 자원 사용 (즉, 자동 닫기) 기능 을 사용해야한다고 지적했습니다 .

try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
}

이와 같은 문자열을 읽을 때 일반적으로 줄마다 문자열 처리를 원 하므로이 구현으로 이동합니다.

실제로 파일을 문자열로 읽으려면 항상 Apache Commons IO를 사용합니다. IOUtils.toString () 클래스와 함께 사용하십시오. 여기서 소스를 살펴볼 수 있습니다.

http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.html

FileInputStream inputStream = new FileInputStream("foo.txt");
try {
    String everything = IOUtils.toString(inputStream);
} finally {
    inputStream.close();
}

Java 7보다 훨씬 간단합니다.

try(FileInputStream inputStream = new FileInputStream("foo.txt")) {     
    String everything = IOUtils.toString(inputStream);
    // do something with everything string
}

6
마지막 줄에 도달하면 줄 바꿈 (\ n)을 추가하지 않도록 약간 조정했습니다. code while (line! = null) {sb.append (line); 라인 = br.readLine (); // curline이 마지막 줄이 아닌 경우에만 새 줄을 추가합니다. if (line! = null) {sb.append ( "\ n"); }}code
Ramon Fincken

2
Apache Common IO와 유사하게 IOUtils # toString ()은 sun.misc.IOUtils # readFully ()이며 Sun / Oracle JRE에 포함되어 있습니다.
gb96

3
성능은 항상 sb.append 전화를 들어 ( '\ n')는 문자가 빠른 문자열보다 StringBuilder에 추가됩니다으로 sb.append에 우선하여 ( "\ n")로
GB96

2
FileReader는 FileNotFoundException을 발생시키고 BufferedRead는 IOException을 발생시킬 수 있으므로이를 잡아야합니다.
kamaci

4
독자를 직접 사용할 필요가 없으며 ioutils가 필요하지 않습니다. java7에는 전체 파일 / 모든 행을 읽는 메소드가 내장되어 있습니다. docs.oracle.com/javase/7/docs/api/java/nio/file/…docs.oracle.com/javase/7/docs/api를
kritzikratzi

142

가장 쉬운 방법은 ScannerJava 및 FileReader 객체에서 클래스 를 사용하는 것입니다. 간단한 예 :

Scanner in = new Scanner(new FileReader("filename.txt"));

Scanner 문자열, 숫자 등을 읽는 몇 가지 방법이 있습니다. 자세한 내용은 Java 설명서 페이지를 참조하십시오.

예를 들어 전체 내용을 String:

StringBuilder sb = new StringBuilder();
while(in.hasNext()) {
    sb.append(in.next());
}
in.close();
outString = sb.toString();

또한 특정 인코딩이 필요한 경우 대신 다음을 사용할 수 있습니다 FileReader.

new InputStreamReader(new FileInputStream(fileUtf8), StandardCharsets.UTF_8)

28
while (in.hasNext ()) {System.out.println (in.next ()); }
Gene Bo

16
@Hissain 그러나보다 사용하기가 훨씬 쉽습니다BufferedReader
Jesus Ramos

3
Catch
Rahal Kanishka

@JesusRamos 왜 그렇게 생각하지 않습니까? 이것보다 더 쉬운 것은 무엇입니까 while ((line = br.readLine()) != null) { sb.append(line); }?
user207421

83

간단한 해결책은 다음과 같습니다.

String content;

content = new String(Files.readAllBytes(Paths.get("sample.txt")));

2
@Nery Jr, 우아하고 단순함
Mahmoud Saleh

1
가장 좋고 가장 간단합니다.
Dary

57

외부 라이브러리를 사용하지 않고 다른 방법을 사용하십시오.

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public String readFile(String filename)
{
    String content = null;
    File file = new File(filename); // For example, foo.txt
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        char[] chars = new char[(int) file.length()];
        reader.read(chars);
        content = new String(chars);
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(reader != null){
            reader.close();
        }
    }
    return content;
}

10
또는 "자원을 사용하여 시도" try (FileReader reader = new FileReader (file)) 사용
Hernán Eche

3
file.length (), utf-16 파일에서 얼마나 잘 작동합니까?
Wayne

5
이 기법은 read ()가 버퍼를 채우는 것으로 가정합니다. 문자 수는 바이트 수와 같습니다. 바이트 수는 메모리에 맞습니다. 바이트 수는 정수에 맞습니다. -1
207421

1
@HermesTrismegistus 나는 그것이 왜 틀린지 네 가지 이유를 제시했다. StefanReich는 저에게 동의하는 것이 완벽합니다.
user207421

34

다른 방법으로 벤치마킹해야했습니다. 내 발견에 대해서는 언급해야하지만, 가장 빠른 방법은 FileInputStream을 통해 일반 BufferedInputStream을 사용하는 것입니다. 많은 파일을 읽어야하는 경우 세 개의 스레드는 총 실행 시간을 대략 절반으로 줄이지 만 더 많은 스레드를 추가하면 하나의 스레드보다 20 개의 스레드로 완료하는 데 3 배가 더 걸릴 때까지 성능이 점차 저하됩니다.

파일을 읽고 그 내용으로 의미있는 것을 수행해야한다고 가정합니다. 이 예에서는 로그에서 행을 읽고 특정 임계 값을 초과하는 값을 포함하는 행을 계산합니다. 그래서 나는 한 줄짜리 Java 8이라고 가정합니다.Files.lines(Paths.get("/path/to/file.txt")).map(line -> line.split(";")) 이 옵션이 아니라고 .

Java 1.8, Windows 7 및 SSD 및 HDD 드라이브 모두에서 테스트했습니다.

나는 여섯 가지 다른 구현을 썼다.

rawParse : FileInputStream에 대해 BufferedInputStream을 사용한 다음 바이트 단위로 읽는 행을 잘라냅니다. 이것은 다른 단일 스레드 접근 방식보다 성능이 뛰어나지 만 비 ASCII 파일에는 매우 불편할 수 있습니다.

lineReaderParse : FileReader에서 BufferedReader를 사용하고 한 줄씩 읽고 String.split ()을 호출하여 줄을 나눕니다. rawParse보다 약 20 % 느립니다.

lineReaderParseParallel : lineReaderParse 와 동일하지만 여러 스레드를 사용합니다. 모든 경우에서 가장 빠른 옵션입니다.

nioFilesParse : java.nio.files.Files.lines () 사용

nioAsyncParse : 완료 핸들러 및 스레드 풀과 함께 AsynchronousFileChannel을 사용하십시오.

nioMemoryMappedParse : 메모리 매핑 된 파일을 사용하십시오. 이것은 실제로 다른 구현보다 최소 3 배 더 긴 실행 시간을 산출하는 나쁜 아이디어입니다.

쿼드 코어 i7 및 SSD 드라이브에서 각각 4MB의 204 파일을 읽는 데 걸리는 평균 시간입니다. 디스크 캐싱을 피하기 위해 파일이 즉시 생성됩니다.

rawParse                11.10 sec
lineReaderParse         13.86 sec
lineReaderParseParallel  6.00 sec
nioFilesParse           13.52 sec
nioAsyncParse           16.06 sec
nioMemoryMappedParse    37.68 sec

SSD에서 실행하거나 HDD 드라이브가 SSD에서 약 15 % 더 빠를 때의 예상보다 작은 차이를 발견했습니다. 파일이 조각화되지 않은 HDD에서 생성되고 순차적으로 읽혀지기 때문에 회전 드라이브가 거의 SSD처럼 작동 할 수 있습니다.

nioAsyncParse 구현의 성능이 저하되어 놀랐습니다. 내가 잘못된 방식으로 무언가를 구현했거나 NIO를 사용하는 멀티 스레드 구현 및 완료 핸들러는 java.io API를 사용한 단일 스레드 구현과 동일하거나 더 나쁜 성능을 수행합니다. 또한 CompletionHandler를 사용한 비동기 구문 분석은 코드 줄이 훨씬 길고 이전 스트림의 직선 구현보다 올바르게 구현하기가 까다로워집니다.

이제 6 개의 구현 다음에 모두 포함 된 클래스와 파일 수, 파일 크기 및 동시성 정도를 재생할 수있는 매개 변수화 가능한 main () 메소드가 포함됩니다. 파일의 크기에 20에서 20을 더한 값이 다릅니다. 이것은 모든 파일이 정확히 같은 크기이기 때문에 어떠한 영향도 피하기위한 것입니다.

rawParse

public void rawParse(final String targetDir, final int numberOfFiles) throws IOException, ParseException {
    overrunCount = 0;
    final int dl = (int) ';';
    StringBuffer lineBuffer = new StringBuffer(1024);
    for (int f=0; f<numberOfFiles; f++) {
        File fl = new File(targetDir+filenamePreffix+String.valueOf(f)+".txt");
        FileInputStream fin = new FileInputStream(fl);
        BufferedInputStream bin = new BufferedInputStream(fin);
        int character;
        while((character=bin.read())!=-1) {
            if (character==dl) {

                // Here is where something is done with each line
                doSomethingWithRawLine(lineBuffer.toString());
                lineBuffer.setLength(0);
            }
            else {
                lineBuffer.append((char) character);
            }
        }
        bin.close();
        fin.close();
    }
}

public final void doSomethingWithRawLine(String line) throws ParseException {
    // What to do for each line
    int fieldNumber = 0;
    final int len = line.length();
    StringBuffer fieldBuffer = new StringBuffer(256);
    for (int charPos=0; charPos<len; charPos++) {
        char c = line.charAt(charPos);
        if (c==DL0) {
            String fieldValue = fieldBuffer.toString();
            if (fieldValue.length()>0) {
                switch (fieldNumber) {
                    case 0:
                        Date dt = fmt.parse(fieldValue);
                        fieldNumber++;
                        break;
                    case 1:
                        double d = Double.parseDouble(fieldValue);
                        fieldNumber++;
                        break;
                    case 2:
                        int t = Integer.parseInt(fieldValue);
                        fieldNumber++;
                        break;
                    case 3:
                        if (fieldValue.equals("overrun"))
                            overrunCount++;
                        break;
                }
            }
            fieldBuffer.setLength(0);
        }
        else {
            fieldBuffer.append(c);
        }
    }
}

lineReaderParse

public void lineReaderParse(final String targetDir, final int numberOfFiles) throws IOException, ParseException {
    String line;
    for (int f=0; f<numberOfFiles; f++) {
        File fl = new File(targetDir+filenamePreffix+String.valueOf(f)+".txt");
        FileReader frd = new FileReader(fl);
        BufferedReader brd = new BufferedReader(frd);

        while ((line=brd.readLine())!=null)
            doSomethingWithLine(line);
        brd.close();
        frd.close();
    }
}

public final void doSomethingWithLine(String line) throws ParseException {
    // Example of what to do for each line
    String[] fields = line.split(";");
    Date dt = fmt.parse(fields[0]);
    double d = Double.parseDouble(fields[1]);
    int t = Integer.parseInt(fields[2]);
    if (fields[3].equals("overrun"))
        overrunCount++;
}

lineReaderParseParallel

public void lineReaderParseParallel(final String targetDir, final int numberOfFiles, final int degreeOfParalelism) throws IOException, ParseException, InterruptedException {
    Thread[] pool = new Thread[degreeOfParalelism];
    int batchSize = numberOfFiles / degreeOfParalelism;
    for (int b=0; b<degreeOfParalelism; b++) {
        pool[b] = new LineReaderParseThread(targetDir, b*batchSize, b*batchSize+b*batchSize);
        pool[b].start();
    }
    for (int b=0; b<degreeOfParalelism; b++)
        pool[b].join();
}

class LineReaderParseThread extends Thread {

    private String targetDir;
    private int fileFrom;
    private int fileTo;
    private DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private int overrunCounter = 0;

    public LineReaderParseThread(String targetDir, int fileFrom, int fileTo) {
        this.targetDir = targetDir;
        this.fileFrom = fileFrom;
        this.fileTo = fileTo;
    }

    private void doSomethingWithTheLine(String line) throws ParseException {
        String[] fields = line.split(DL);
        Date dt = fmt.parse(fields[0]);
        double d = Double.parseDouble(fields[1]);
        int t = Integer.parseInt(fields[2]);
        if (fields[3].equals("overrun"))
            overrunCounter++;
    }

    @Override
    public void run() {
        String line;
        for (int f=fileFrom; f<fileTo; f++) {
            File fl = new File(targetDir+filenamePreffix+String.valueOf(f)+".txt");
            try {
            FileReader frd = new FileReader(fl);
            BufferedReader brd = new BufferedReader(frd);
            while ((line=brd.readLine())!=null) {
                doSomethingWithTheLine(line);
            }
            brd.close();
            frd.close();
            } catch (IOException | ParseException ioe) { }
        }
    }
}

nioFilesParse

public void nioFilesParse(final String targetDir, final int numberOfFiles) throws IOException, ParseException {
    for (int f=0; f<numberOfFiles; f++) {
        Path ph = Paths.get(targetDir+filenamePreffix+String.valueOf(f)+".txt");
        Consumer<String> action = new LineConsumer();
        Stream<String> lines = Files.lines(ph);
        lines.forEach(action);
        lines.close();
    }
}


class LineConsumer implements Consumer<String> {

    @Override
    public void accept(String line) {

        // What to do for each line
        String[] fields = line.split(DL);
        if (fields.length>1) {
            try {
                Date dt = fmt.parse(fields[0]);
            }
            catch (ParseException e) {
            }
            double d = Double.parseDouble(fields[1]);
            int t = Integer.parseInt(fields[2]);
            if (fields[3].equals("overrun"))
                overrunCount++;
        }
    }
}

nioAsyncParse

public void nioAsyncParse(final String targetDir, final int numberOfFiles, final int numberOfThreads, final int bufferSize) throws IOException, ParseException, InterruptedException {
    ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(numberOfThreads);
    ConcurrentLinkedQueue<ByteBuffer> byteBuffers = new ConcurrentLinkedQueue<ByteBuffer>();

    for (int b=0; b<numberOfThreads; b++)
        byteBuffers.add(ByteBuffer.allocate(bufferSize));

    for (int f=0; f<numberOfFiles; f++) {
        consumerThreads.acquire();
        String fileName = targetDir+filenamePreffix+String.valueOf(f)+".txt";
        AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(fileName), EnumSet.of(StandardOpenOption.READ), pool);
        BufferConsumer consumer = new BufferConsumer(byteBuffers, fileName, bufferSize);
        channel.read(consumer.buffer(), 0l, channel, consumer);
    }
    consumerThreads.acquire(numberOfThreads);
}


class BufferConsumer implements CompletionHandler<Integer, AsynchronousFileChannel> {

        private ConcurrentLinkedQueue<ByteBuffer> buffers;
        private ByteBuffer bytes;
        private String file;
        private StringBuffer chars;
        private int limit;
        private long position;
        private DateFormat frmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        public BufferConsumer(ConcurrentLinkedQueue<ByteBuffer> byteBuffers, String fileName, int bufferSize) {
            buffers = byteBuffers;
            bytes = buffers.poll();
            if (bytes==null)
                bytes = ByteBuffer.allocate(bufferSize);

            file = fileName;
            chars = new StringBuffer(bufferSize);
            frmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            limit = bufferSize;
            position = 0l;
        }

        public ByteBuffer buffer() {
            return bytes;
        }

        @Override
        public synchronized void completed(Integer result, AsynchronousFileChannel channel) {

            if (result!=-1) {
                bytes.flip();
                final int len = bytes.limit();
                int i = 0;
                try {
                    for (i = 0; i < len; i++) {
                        byte by = bytes.get();
                        if (by=='\n') {
                            // ***
                            // The code used to process the line goes here
                            chars.setLength(0);
                        }
                        else {
                                chars.append((char) by);
                        }
                    }
                }
                catch (Exception x) {
                    System.out.println(
                        "Caught exception " + x.getClass().getName() + " " + x.getMessage() +
                        " i=" + String.valueOf(i) + ", limit=" + String.valueOf(len) +
                        ", position="+String.valueOf(position));
                }

                if (len==limit) {
                    bytes.clear();
                    position += len;
                    channel.read(bytes, position, channel, this);
                }
                else {
                    try {
                        channel.close();
                    }
                    catch (IOException e) {
                    }
                    consumerThreads.release();
                    bytes.clear();
                    buffers.add(bytes);
                }
            }
            else {
                try {
                    channel.close();
                }
                catch (IOException e) {
                }
                consumerThreads.release();
                bytes.clear();
                buffers.add(bytes);
            }
        }

        @Override
        public void failed(Throwable e, AsynchronousFileChannel channel) {
        }
};

모든 사례의 완전한 실행 가능한 구현

https://github.com/sergiomt/javaiobenchmark/blob/master/FileReadBenchmark.java


24

다음은 세 가지 작동 및 테스트 방법입니다.

사용 BufferedReader

package io;
import java.io.*;
public class ReadFromFile2 {
    public static void main(String[] args)throws Exception {
        File file = new File("C:\\Users\\pankaj\\Desktop\\test.java");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String st;
        while((st=br.readLine()) != null){
            System.out.println(st);
        }
    }
}

사용 Scanner

package io;

import java.io.File;
import java.util.Scanner;

public class ReadFromFileUsingScanner {
    public static void main(String[] args) throws Exception {
        File file = new File("C:\\Users\\pankaj\\Desktop\\test.java");
        Scanner sc = new Scanner(file);
        while(sc.hasNextLine()){
            System.out.println(sc.nextLine());
        }
    }
}

사용 FileReader

package io;
import java.io.*;
public class ReadingFromFile {

    public static void main(String[] args) throws Exception {
        FileReader fr = new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
        int i;
        while ((i=fr.read()) != -1){
            System.out.print((char) i);
        }
    }
}

Scanner클래스를 사용하여 루프없이 전체 파일을 읽습니다.

package io;

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:\\Users\\pankaj\\Desktop\\test.java");
        Scanner sc = new Scanner(file);
        sc.useDelimiter("\\Z");
        System.out.println(sc.next());
    }
}

1
폴더가 프로젝트 내에있는 경우 경로를 지정하는 방법은 무엇입니까?
Kavipriya

2
무엇에 대해 java.nio.file.Files? 우리는 지금 바로 사용할 수 있습니다 readAllLines, readAllBytes하고 lines.
클로드 마틴

21

org.apache.commons.io.FileUtils예를 들어, 다음과 같은 방법 이 매우 유용 할 수 있습니다.

/**
 * Reads the contents of a file line by line to a List
 * of Strings using the default encoding for the VM.
 */
static List readLines(File file)

또는 보다 현대적이고 적극적으로 유지 관리되는 라이브러리 인 Guava 를 선호하는 경우 Files 클래스 에 유사한 유틸리티가 있습니다. 이 답변의 간단한 예 .
Jonik

1
또는 단순히 내장 메소드를 사용하여 모든 행을 가져옵니다. docs.oracle.com/javase/7/docs/api/java/nio/file/…
kritzikratzi

아파치 커먼즈에 대한 링크가 죽은 것 같습니다.
kebs

17

텍스트로 무엇을하고 싶습니까? 파일이 메모리에 들어갈만큼 작습니까? 귀하의 요구에 맞는 파일을 처리하는 가장 간단한 방법을 찾으려고 노력합니다. FileUtils 라이브러리는이를 처리합니다.

for(String line: FileUtils.readLines("my-text-file"))
    System.out.println(line);

2
또한 java7에 내장되어 있습니다. docs.oracle.com/javase/7/docs/api/java/nio/file/…
kritzikratzi

@PeterLawrey는 아마도 의미 org.apache.commons.io.FileUtils합니다. 가장 광범위한 의미가 바뀌면서 Google 링크는 시간이 지남에 따라 콘텐츠를 변경할 수 있지만 이는 검색어와 일치하며 올바르게 보입니다.
Palec

2
불행하게도, 요즘이 더 없습니다 readLines(String)readLines(File)찬성되지 않습니다 readLines(File, Charset). 인코딩은 문자열로도 제공 될 수 있습니다.
Palec


12

Java로 파일을 읽는 15 가지 방법을 문서화 한 다음 1KB에서 1GB까지 다양한 파일 크기의 속도로 테스트했습니다.이를 수행하는 가장 좋은 세 가지 방법은 다음과 같습니다.

  1. java.nio.file.Files.readAllBytes()

    Java 7, 8 및 9에서 작동하도록 테스트되었습니다.

    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Files;
    
    public class ReadFile_Files_ReadAllBytes {
      public static void main(String [] pArgs) throws IOException {
        String fileName = "c:\\temp\\sample-10KB.txt";
        File file = new File(fileName);
    
        byte [] fileBytes = Files.readAllBytes(file.toPath());
        char singleChar;
        for(byte b : fileBytes) {
          singleChar = (char) b;
          System.out.print(singleChar);
        }
      }
    }
  2. java.io.BufferedReader.readLine()

    Java 7, 8, 9에서 작동하도록 테스트되었습니다.

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class ReadFile_BufferedReader_ReadLine {
      public static void main(String [] args) throws IOException {
        String fileName = "c:\\temp\\sample-10KB.txt";
        FileReader fileReader = new FileReader(fileName);
    
        try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
          String line;
          while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
          }
        }
      }
    }
  3. java.nio.file.Files.lines()

    이것은 Java 8 및 9에서 작동하도록 테스트되었지만 람다 식 요구 사항으로 인해 Java 7에서는 작동하지 않습니다.

    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.util.stream.Stream;
    
    public class ReadFile_Files_Lines {
      public static void main(String[] pArgs) throws IOException {
        String fileName = "c:\\temp\\sample-10KB.txt";
        File file = new File(fileName);
    
        try (Stream linesStream = Files.lines(file.toPath())) {
          linesStream.forEach(line -> {
            System.out.println(line);
          });
        }
      }
    }

9

아래는 Java 8 방식으로 수행하는 한 줄짜리입니다. text.txt파일이 Eclipse의 프로젝트 디렉토리 루트에 있다고 가정 하십시오.

Files.lines(Paths.get("text.txt")).collect(Collectors.toList());

7

BufferedReader 사용 :

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

BufferedReader br;
try {
    br = new BufferedReader(new FileReader("/fileToRead.txt"));
    try {
        String x;
        while ( (x = br.readLine()) != null ) {
            // Printing out each line in the file
            System.out.println(x);
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}
catch (FileNotFoundException e) {
    System.out.println(e);
    e.printStackTrace();
}

7

이것은 FileReader 대신 File을 사용 하고 파일 의 내용을 단계별로 반복하는 것을 제외하고는 기본적으로 Jesus Ramos의 대답과 동일 합니다.

Scanner in = new Scanner(new File("filename.txt"));

while (in.hasNext()) { // Iterates each line in the file
    String line = in.nextLine();
    // Do something with line
}

in.close(); // Don't forget to close resource leaks

... 던졌습니다 FileNotFoundException


3
File vs FileReader : FileReader를 사용하면 파일이 존재하고 운영 체제 권한이 액세스를 허용해야합니다. 파일을 사용하면 해당 권한을 테스트하거나 파일이 디렉토리인지 확인할 수 있습니다. 파일에는 유용한 함수가 있습니다 : isFile (), isDirectory (), listFiles (), canExecute (), canRead (), canWrite (), exist (), mkdir (), delete (). File.createTempFile ()은 시스템 기본 임시 디렉토리에 씁니다. 이 메소드는 FileOutputStream 오브젝트 등을 여는 데 사용할 수있는 파일 오브젝트를 리턴합니다. source
ThisClark

7

버퍼링 된 스트림 클래스는 실제로 성능이 훨씬 뛰어나므로 NIO.2 API에는 이러한 스트림 클래스를 구체적으로 반환하는 메소드가 포함되어있어 애플리케이션에서 항상 버퍼링 된 스트림을 항상 사용하도록 권장합니다.

예를 들면 다음과 같습니다.

Path path = Paths.get("/myfolder/myfile.ext");
try (BufferedReader reader = Files.newBufferedReader(path)) {
    // Read from the stream
    String currentLine = null;
    while ((currentLine = reader.readLine()) != null)
        //do your code here
} catch (IOException e) {
    // Handle file I/O exception...
}

이 코드를 바꿀 수 있습니다

BufferedReader reader = Files.newBufferedReader(path);

BufferedReader br = new BufferedReader(new FileReader("/myfolder/myfile.ext"));

Java NIO 및 IO의 주요 사용법을 배우려면 기사를 추천 합니다 .


6

아마도 버퍼링 된 I / O만큼 빠르지는 않지만 상당히 간결합니다.

    String content;
    try (Scanner scanner = new Scanner(textFile).useDelimiter("\\Z")) {
        content = scanner.next();
    }

\Z패턴은 알려줍니다 Scanner구분 기호가 EOF이다.


1
이미 관련이 있고 이미 존재하는 대답 은 예수 라모스입니다.
Palec

1
if(scanner.hasNext()) content = scanner.next();
David Soroko

1
이것은 Android 4.4에서 실패합니다. 1024 바이트 만 읽습니다. YMMV.
Roger Keays

3

나는 지금까지 다른 답변에서 아직 언급되지 않았습니다. 그러나 "최고"가 속도를 의미한다면 새로운 Java I / O (NIO)가 가장 빠른 성능을 제공하지만 항상 배우는 사람에게 가장 쉬운 것은 아닙니다.

http://download.oracle.com/javase/tutorial/essential/io/file.html


어떻게했는지와 언급 할 링크를주지 말아야합니다.
Orar

3

Java로 파일에서 데이터를 읽는 가장 간단한 방법은 File 클래스를 사용하여 파일 을 읽고 Scanner 클래스는 파일의 내용을 읽는 것입니다.

public static void main(String args[])throws Exception
{
   File f = new File("input.txt");
   takeInputIn2DArray(f);
}

public static void takeInputIn2DArray(File f) throws Exception
{
    Scanner s = new Scanner(f);
    int a[][] = new int[20][20];
    for(int i=0; i<20; i++)
    {
        for(int j=0; j<20; j++)
        {
            a[i][j] = s.nextInt();
        }
    }
}

추신 : java.util. *을 가져 오는 것을 잊지 마십시오.; 스캐너가 작동합니다.


2

구아바 는이를 위해 하나의 라이너를 제공합니다.

import com.google.common.base.Charsets;
import com.google.common.io.Files;

String contents = Files.toString(filePath, Charsets.UTF_8);

2

이것은 질문에 대한 정확한 답변이 아닐 수도 있습니다. Java 코드에서 파일 경로를 명시 적으로 지정하지 않고 명령 줄 인수로 읽는 파일을 읽는 또 다른 방법입니다.

다음 코드를 사용하면

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class InputReader{

    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s="";
        while((s=br.readLine())!=null){
            System.out.println(s);
        }
    }
}

그냥 다음으로 실행하십시오.

java InputReader < input.txt

이것은 내용을 읽고 input.txt콘솔에 인쇄합니다.

System.out.println()다음과 같이 명령 행을 통해 특정 파일에 쓸 수도 있습니다.

java InputReader < input.txt > output.txt

이것은 읽고 input.txt쓸 것 output.txt입니다.


2

readAllLines 및 join메소드를 사용하여 전체 파일 컨텐츠를 한 줄로 가져올 수 있습니다 .

String str = String.join("\n",Files.readAllLines(Paths.get("e:\\text.txt")));

ASCII 데이터를 올바르게 읽는 기본적으로 UTF-8 인코딩을 사용합니다.

또한 readAllBytes를 사용할 수 있습니다.

String str = new String(Files.readAllBytes(Paths.get("e:\\text.txt")), StandardCharsets.UTF_8);

readAllBytes가 새 행을 대체하지 않고 새 행이 있기 때문에 더 빠르고 정확하다고 생각 \n합니다 \r\n. 어느 것이 적합한 지 당신의 필요에 달려 있습니다.


1

JSF 기반 Maven 웹 애플리케이션의 경우 ClassLoader와 Resources폴더를 사용 하여 원하는 파일을 읽으십시오.

  1. 읽으려는 파일을 Resources 폴더에 넣으십시오.
  2. Apache Commons IO 종속성을 POM에 넣으십시오.

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>
  3. 아래 코드를 사용하여 읽으십시오 (예 : 아래는 .json 파일에서 읽습니다).

    String metadata = null;
    FileInputStream inputStream;
    try {
    
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        inputStream = (FileInputStream) loader
                .getResourceAsStream("/metadata.json");
        metadata = IOUtils.toString(inputStream);
        inputStream.close();
    }
    catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return metadata;

텍스트 파일, .properties 파일, XSD 스키마 등에 대해서도 동일하게 수행 할 수 있습니다 .


'원하는 파일'에는 사용할 수 없습니다. JAR 또는 WAR 파일로 패키지 된 자원에만 사용할 수 있습니다.
user207421

1

Cactoos 는 다음과 같은 선언적인 단일 라이너를 제공합니다.

new TextOf(new File("a.txt")).asString();

0

구조가 단순하다면 Java 키스를 사용하십시오 .

import static kiss.API.*;

class App {
  void run() {
    String line;
    try (Close in = inOpen("file.dat")) {
      while ((line = readLine()) != null) {
        println(line);
      }
    }
  }
}

0
import java.util.stream.Stream;
import java.nio.file.*;
import java.io.*;

class ReadFile {

 public static void main(String[] args) {

    String filename = "Test.txt";

    try(Stream<String> stream = Files.lines(Paths.get(filename))) {

          stream.forEach(System.out:: println);

    } catch (IOException e) {

        e.printStackTrace();
    }

 }

 }

java 8 Stream을 사용하십시오.


0
try {
  File f = new File("filename.txt");
  Scanner r = new Scanner(f);  
  while (r.hasNextLine()) {
    String data = r.nextLine();
    JOptionPane.showMessageDialog(data);
  }
  r.close();
} catch (FileNotFoundException ex) {
  JOptionPane.showMessageDialog("Error occurred");
  ex.printStackTrace();
}

0

가장 직관적 인 방법은 Java 11에 도입되었습니다. Files.readString

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class App {
    public static void main(String args[]) throws IOException {
        String content = Files.readString(Paths.get("D:\\sandbox\\mvn\\my-app\\my-app.iml"));
        System.out.print(content);
    }
}

PHP는 수십 년 전부터이 사치 를 누 렸습니다! ☺


-3

내가 프로그래밍 한이 코드는 매우 큰 파일의 경우 훨씬 빠릅니다.

public String readDoc(File f) {
    String text = "";
    int read, N = 1024 * 1024;
    char[] buffer = new char[N];

    try {
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);

        while(true) {
            read = br.read(buffer, 0, N);
            text += new String(buffer, 0, read);

            if(read < N) {
                break;
            }
        }
    } catch(Exception ex) {
        ex.printStackTrace();
    }

    return text;
}

10
StringBuilder 대신 간단한 문자열 연결을 사용하면 훨씬 더 빠릅니다.
PhiLho

6
주요 속도 향상은 1MB (1024 * 1024) 블록에서 읽는 것입니다. 그러나 1024 * 1024를 두 번째 arg로 BufferedReader 생성자에 전달하여 간단히 동일한 작업을 수행 할 수 있습니다.
gb96

3
나는 이것이 전혀 테스트되지 않았다고 생각합니다. 사용 +=이 방법으로 당신에게 선형 복잡성해야 작업을위한 차 (!) 복잡성을 제공합니다. 몇 MB 이상의 파일을 크롤링하기 시작합니다. 이 문제를 해결하려면 텍스트 블록을 list <string>에 유지하거나 위에서 언급 한 stringbuilder를 사용해야합니다.
kritzikratzi

5
무엇보다 훨씬 빠릅니까? StringBuffer에 추가하는 것보다 빠르지 는 않습니다 . -1
207421

1
@ gb96 버퍼 크기에 대해서는 동일하다고 생각했지만 이 질문에 대한 자세한 실험은 비슷한 맥락에서 놀라운 결과를 제공했습니다. 16KB 버퍼는 일관되고 눈에 띄게 빠릅니다.
chiastic-security

-3
String fileName = 'yourFileFullNameWithPath';
File file = new File(fileName); // Creates a new file object for your file
FileReader fr = new FileReader(file);// Creates a Reader that you can use to read the contents of a file read your file
BufferedReader br = new BufferedReader(fr); //Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

위의 행 집합은 다음과 같이 한 줄에 쓸 수 있습니다.

BufferedReader br = new BufferedReader(new FileReader("file.txt")); // Optional

문자열 빌더에 추가 (파일이 크면 문자열 빌더를 사용하고 그렇지 않으면 일반 문자열 객체를 사용하는 것이 좋습니다)

try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
        }
        String everything = sb.toString();
        } finally {
        br.close();
    }
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.