Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

java - 用Java读取纯文本文件(Reading a plain text file in Java)

It seems there are different ways to read and write data of files in Java.

(似乎有多种方法可以用Java读写文件数据。)

I want to read ASCII data from a file.

(我想从文件中读取ASCII数据。)

What are the possible ways and their differences?

(有哪些可能的方法及其区别?)

  ask by Tim the Enchanter translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My favorite way to read a small file is to use a BufferedReader and a StringBuilder.

(我最喜欢的读取小文件的方法是使用BufferedReader和StringBuilder。)

It is very simple and to the point (though not particularly effective, but good enough for most cases):

(这很简单并且很关键(尽管不是特别有效,但是对于大多数情况来说已经足够了):)

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

Some has pointed out that after Java 7 you should use try-with-resources (ie auto close) features:

(有人指出,在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();
}

When I read strings like this, I usually want to do some string handling per line anyways, so then I go for this implementation.

(当我读取这样的字符串时,无论如何我通常还是想对每行进行一些字符串处理,因此我继续进行此实现。)

Though if I want to actually just read a file into a String, I always use Apache Commons IO with the class IOUtils.toString() method.

(尽管实际上我只是想将文件读入字符串,但我始终将Apache Commons IO与IOUtils.toString()方法一起使用。)

You can have a look at the source here:

(您可以在这里查看源代码:)

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

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

And even simpler with Java 7:

(使用Java 7甚至更简单:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...