在Java中,似乎有不同的方式来读取和写入文件数据。

我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?


当前回答

如果您有一个大文件,您可以使用Apache Commons IO迭代处理该文件,而不会耗尽可用内存。

try (LineIterator it = FileUtils.lineIterator(theFile, "UTF-8")) {
    while (it.hasNext()) {
        String line = it.nextLine();
        // do something with line
    }
}

其他回答

使用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();
}

这里有另一种不使用外部库的方法:

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;
}

我记录了15种用Java读取文件的方法,然后测试了它们在不同文件大小下的速度——从1kb到1gb,下面是最常用的三种方法:

java.nio.file.Files.readAllBytes() Tested to work in Java 7, 8, and 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); } } } java.io.BufferedReader.readLine() Tested to work in 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); } } } } java.nio.file.Files.lines() This was tested to work in Java 8 and 9 but won't work in Java 7 because of the lambda expression requirement. 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); }); } } }

ASCII是一个文本文件,因此您可以使用reader进行读取。Java还支持使用InputStreams从二进制文件中读取。如果要读取的文件很大,那么您可能希望在FileReader之上使用BufferedReader来提高读取性能。

阅读这篇关于如何使用Reader的文章

我还推荐你下载并阅读这本很棒(但免费)的书,叫做《用Java思考》

在Java 7中:

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

(文档) 或

Files.readAllLines(...)

(文档)

在Java 8中:

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

(文档)

我最喜欢的读取小文件的方法是使用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-with-resources(即自动关闭)功能:

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
}