IT-Swarm.Net

如何使用Java逐行读取大型文本文件?

我需要使用Java逐行读取大约5-6 GB的大文本文件。.

我该怎么办?

770
manoj singh

一种常见的模式是使用

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
       // process the line.
    }
}

如果假设没有字符编码,则可以更快地读取数据。例如ASCII-7但它没有太大的区别。您对数据的处理很可能需要更长的时间。.

编辑:一种不太常见的模式,可以避免line泄漏的范围。.

try(BufferedReader br = new BufferedReader(new FileReader(file))) {
    for(String line; (line = br.readLine()) != null; ) {
        // process the line.
    }
    // line is not visible here.
}

更新:在Java 8中你可以做到

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
        stream.forEach(System.out::println);
}

注意:您必须将Stream放在 try-with-resource 块中以确保在其上调用#close方法,否则基础文件句柄永远不会关闭,直到GC稍后执行它。.

953
Peter Lawrey

看看这个博客:

可以指定缓冲区大小,或可以使用默认大小。 默认值足以满足大多数目的。.

// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

String strLine;

//Read File Line By Line
while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
  System.out.println (strLine);
}

//Close the input stream
fstream.close();
133
Naveed

一旦 Java-8 即将结束(2014年3月),您将能够使用流:

try (Stream<String> lines = Files.lines(Paths.get(filename), Charset.defaultCharset())) {
  lines.forEachOrdered(line -> process(line));
}

打印文件中的所有行:

try (Stream<String> lines = Files.lines(file, Charset.defaultCharset())) {
  lines.forEachOrdered(System.out::println);
}
82
msayag

下面是一个完整的错误处理和支持Java 7之前的charset规范的示例。使用Java 7,您可以使用try-with-resources语法,这使代码更清晰。.

如果您只想要默认的字符集,可以跳过InputStream并使用FileReader。.

InputStream ins = null; // raw byte-stream
Reader r = null; // cooked reader
BufferedReader br = null; // buffered for readLine()
try {
    String s;
    ins = new FileInputStream("textfile.txt");
    r = new InputStreamReader(ins, "UTF-8"); // leave charset out for default
    br = new BufferedReader(r);
    while ((s = br.readLine()) != null) {
        System.out.println(s);
    }
}
catch (Exception e)
{
    System.err.println(e.getMessage()); // handle exception
}
finally {
    if (br != null) { try { br.close(); } catch(Throwable t) { /* ensure close happens */ } }
    if (r != null) { try { r.close(); } catch(Throwable t) { /* ensure close happens */ } }
    if (ins != null) { try { ins.close(); } catch(Throwable t) { /* ensure close happens */ } }
}

这是Groovy版本,具有完整的错误处理:

File f = new File("textfile.txt");
f.withReader("UTF-8") { br ->
    br.eachLine { line ->
        println line;
    }
}
35
DarkStar

在Java 8中,您可以:

try (Stream<String> lines = Files.lines (file, StandardCharsets.UTF_8))
{
    for (String line : (Iterable<String>) lines::iterator)
    {
        ;
    }
}

一些注意事项:Files.lines返回的流(与大多数流不同)需要关闭。由于 这里提到的原因 我避免使用forEach()。奇怪的代码(Iterable<String>) lines::iterator将Stream转换为Iterable。.

21
Aleksandr Dubinsky

您可以做的是使用扫描仪扫描整个文本并逐行浏览文本。当然您应该导入以下内容:

import Java.io.File;
import Java.io.FileNotFoundException;
import Java.util.Scanner;
public static void readText throws FileNotFoundException {
    Scanner scan = new Scanner(new File("samplefilename.txt"));
    while(scan.hasNextLine()){
        String line = scan.nextLine();
        //Here you can manipulate the string the way you want
    }
}

扫描仪基本上扫描所有文本。 while循环用于遍历整个文本。.

.hasNextLine()函数是一个布尔值,如果文本中还有更多行,则返回true。 .nextLine()函数为您提供整行作为字符串,然后您可以按照您想要的方式使用。尝试System.out.println(line)打印文本。.

附注:.txt是文件类型文本。.

19
iskandarchacra

FileReader不允许您指定编码,如果需要指定,请使用InputStreamReaderinstead:

try {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "Cp1252"));         

    String line;
    while ((line = br.readLine()) != null) {
        // process the line.
    }
    br.close();

} catch (IOException e) {
    e.printStackTrace();
}

如果从Windows导入此文件,则它可能具有ANSI编码(Cp1252),因此您必须指定编码。 

17
live-love

在Java 7中:

String folderPath = "C:/folderOfMyFile";
Path path = Paths.get(folderPath, "myFileName.csv"); //or any text file eg.: txt, bat, etc
Charset charset = Charset.forName("UTF-8");

try (BufferedReader reader = Files.newBufferedReader(path , charset)) {
  while ((line = reader.readLine()) != null ) {
    //separate all csv fields into string array
    String[] lineVariables = line.split(","); 
  }
} catch (IOException e) {
    System.err.println(e);
}
15
Diego Duarte

我记录并测试了 用Java读取文件的10种不同方法 然后通过将它们读入1KB到1GB的测试文件来相互运行它们。以下是读取1GB测试文件的最快3种文件读取方法。.

请注意,在运行性能测试时,我没有向控制台输出任何内容,因为这会降低测试速度。我只想测试原始阅读速度。.

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

在Java 7,8,9中测试过。这是总体上最快的方法。读取1GB文件始终不到1秒。.

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-1GB.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.nio.file.Files.lines()

这已在Java 8和9中成功测试,但由于缺乏对lambda表达式的支持,因此无法在Java 7中运行。在一个1GB的文件中读取大约需要3.5秒才能将其放在第二位,直到读取更大的文件。.

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-1GB.txt";
    File file = new File(fileName);

    try (Stream linesStream = Files.lines(file.toPath())) {
      linesStream.forEach(line -> {
        System.out.println(line);
      });
    }
  }
}

3)BufferedReader

测试工作在Java 7,8,9中。在1GB测试文件中读取大约需要4.5秒。.

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-1GB.txt";
    FileReader fileReader = new FileReader(fileName);

    try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
      String line;
      while((line = bufferedReader.readLine()) != null) {
        System.out.println(line);
      }
    }
  }

你可以找到所有10种文件阅读方法的完整排名 here 。.

11
gomisha

对于 使用Java 8读取文件

  package com.Java.java8;

    import Java.nio.file.Files;
    import Java.nio.file.Paths;
    import Java.util.stream.Stream;

    /**
     * The Class ReadLargeFile.
     *
     * @author Ankit Sood Apr 20, 2017
     */
    public class ReadLargeFile {

        /**
         * The main method.
         *
         * @param args
         *            the arguments
         */
        public static void main(String[] args) {
        try {
            Stream<String> stream = Files.lines(Paths.get("C:\\Users\\System\\Desktop\\demoData.txt"));
            stream.forEach(System.out::println);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
    }
10
Ankit Sood

您可以使用Scanner类

Scanner sc=new Scanner(file);
sc.nextLine();
9
Abhilash

在Java 8中,还有一种使用 Files.lines() 的替代方法。如果您的输入源不是文件,而是像ReaderInputStream这样更抽象的东西,您可以通过BufferedReaders lines()方法 stream 行。.

例如:

try( BufferedReader reader = new BufferedReader( ... ) ) {
  reader.lines().foreach( line -> processLine( line ) );
}

将为BufferedReader读取的每个输入行调用processLine()。.

8
Rüdiger Herrmann

你需要在class BufferedReader中使用readLine()方法。[。_____。]从该类创建一个新对象并对他操作此方法并将其保存为字符串。.

BufferReader Javadoc

7
Master C

Java-9:

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
        stream.forEach(System.out::println);
}
6
Abdennour TOUMI

实现这一目标的明确方法,

例如:

如果您当前目录中有dataFile.txt

import Java.io.*;
import Java.util.Scanner;
import Java.io.FileNotFoundException;

public class readByLine
{
    public readByLine() throws FileNotFoundException
    {
        Scanner linReader = new Scanner(new File("dataFile.txt"));

        while (linReader.hasNext())
        {
            String line = linReader.nextLine();
            System.out.println(line);
        }
        linReader.close();

    }

    public static void main(String args[])  throws FileNotFoundException
    {
        new readByLine();
    }
}

输出如下, enter image description here

5
Rajamohan S
BufferedReader br;
FileInputStream fin;
try {
    fin = new FileInputStream(fileName);
    br = new BufferedReader(new InputStreamReader(fin));

    /*Path pathToFile = Paths.get(fileName);
    br = Files.newBufferedReader(pathToFile,StandardCharsets.US_ASCII);*/

    String line = br.readLine();
    while (line != null) {
        String[] attributes = line.split(",");
        Movie movie = createMovie(attributes);
        movies.add(movie);
        line = br.readLine();
    }
    fin.close();
    br.close();
} catch (FileNotFoundException e) {
    System.out.println("Your Message");
} catch (IOException e) {
    System.out.println("Your Message");
}

这个对我有用。希望它也会对你有所帮助。.

3
Dipendra Ghatal

我通常直接阅读例行程序: 

void readResource(InputStream source) throws IOException {
    BufferedReader stream = null;
    try {
        stream = new BufferedReader(new InputStreamReader(source));
        while (true) {
            String line = stream.readLine();
            if(line == null) {
                break;
            }
            //process line
            System.out.println(line)
        }
    } finally {
        closeQuiet(stream);
    }
}

static void closeQuiet(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException ignore) {
        }
    }
}
2
Binkan Salaryman

通过使用 org.Apache.commons.io package提供了更多性能,尤其是在使用Java 6及更低版本的遗留代码中。.
Java7具有更好的API,更少的例外处理和更有用的方法 

LineIterator lineIterator =null;
    try{
    lineIterator = FileUtils.lineIterator(new File("/home/username/m.log"), "windows-1256");//second parameter is optionanl
    while (lineIterator.hasNext()){
      String currentLine = lineIterator.next();   
     //some operation
    } 
    }finally {  
     LineIterator.closeQuietly(lineIterator);
    }

行家 

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
1
mohsen.nour

您可以使用流来更精确地执行此操作:

Files.lines(Paths.get("input.txt")).forEach(s -> stringBuffer.append(s);
0
spidy

你也可以使用Apache commons io

File file = new File("/home/user/file.txt");
try {
    List<String> lines = FileUtils.readLines(file);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
0
To Kra

您可以使用此代码:

import Java.io.BufferedReader;
import Java.io.File;
import Java.io.FileReader;
import Java.io.IOException;

public class ReadTextFile {

    public static void main(String[] args) throws IOException {

        try {

            File f = new File("src/com/data.txt");

            BufferedReader b = new BufferedReader(new FileReader(f));

            String readLine = "";

            System.out.println("Reading file using Buffered Reader");

            while ((readLine = b.readLine()) != null) {
                System.out.println(readLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
0
Usman Yaqoob