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

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


当前回答

Cactoos提供了一个声明性的一行代码:

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

其他回答

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)

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

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

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

在Java 7中:

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

(文档) 或

Files.readAllLines(...)

(文档)

在Java 8中:

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

(文档)

这可能不是问题的确切答案。这只是读取文件的另一种方式,其中不需要在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。

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

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

你可以使用readAllLines和join方法在一行中获取整个文件内容:

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

它默认使用UTF-8编码,可以正确读取ASCII数据。

你也可以使用readAllBytes:

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

我认为readAllBytes更快更精确,因为它不会用\n替换新行,也不会用\r\n替换新行。哪一种合适取决于你的需要。