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

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


当前回答

我记录了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); }); } } }

其他回答

在实践中,缓冲流类的性能要高得多,以至于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的主要用途。

我编写的这段代码对于非常大的文件要快得多:

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

对于使用Kotlin的Android开发者来说:

val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val text = myFileUrl.readText() // Not recommended for huge files
println(text)

其他解决方案:

val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val file = File(myFileUrl.toURI())
val lines = file.readLines() // Not recommended for huge files
lines.forEach(::println)

另一个很好的解决方案,也可以用于大文件:

val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val file = File(myFileUrl.toURI())
file
    .bufferedReader()
    .lineSequence()
    .forEach(::println)

Or:

val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val file = File(myFileUrl.toURI())
file.useLines { lines ->
    lines.forEach(::println)
}

注:

txt文件应该在您的类路径中(例如,在src/main/resources目录中) 上述解决方案都默认将文件编码处理为UTF-8。您可以指定所需的编码作为函数的参数。 上述解决方案不需要任何进一步的操作,如关闭文件或读取器。它们由Kotlin标准库自动处理。

你想怎么处理这篇文章?文件是否小到可以装入内存?我会尽量找到最简单的方法来处理您需要的文件。FileUtils库可以很好地处理这个问题。

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

我记录了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); }); } } }