42

要获取 txt 文件的内容,我通常使用扫描仪并遍历每一行以获取内容:

Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();                     
}

java api是否提供了一种通过一行代码获取内容的方法,例如:

String content = FileUtils.readFileToString(new File("file.txt"))
4

6 回答 6

33

不是内置 API - 但Guava确实如此,以及它的其他宝藏。(这是一个很棒的图书馆。)

String content = Files.toString(new File("file.txt"), Charsets.UTF_8);

有类似的方法可以读取任何 Readable,或将二进制文件的全部内容加载为字节数组,或将文件读入字符串列表等。

请注意,此方法现已弃用。新的等价物是:

String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read();
于 2011-04-12T20:17:53.487 回答
25

在 Java 7 中,有一个类似这些方面的 API。

Files.readAllLines(路径路径,字符集 cs)

于 2011-04-12T20:18:35.083 回答
20

commons-io有:

IOUtils.toString(new FileReader("file.txt"), "utf-8");
于 2011-04-12T20:21:17.480 回答
11
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public static void main(String[] args) throws IOException {
    String content = Files.readString(Paths.get("foo"));
}

来自https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)

于 2016-05-26T16:06:47.220 回答
7

您可以将 FileReader 类与 BufferedReader 一起使用来读取文本文件。

File fileToRead = new File("file.txt");

try( FileReader fileStream = new FileReader( fileToRead ); 
    BufferedReader bufferedReader = new BufferedReader( fileStream ) ) {

    String line = null;

    while( (line = bufferedReader.readLine()) != null ) {
        //do something with line
    }

    } catch ( FileNotFoundException ex ) {
        //exception Handling
    } catch ( IOException ex ) {
        //exception Handling
}
于 2016-10-27T12:04:30.893 回答
0

经过一番测试,我发现在各种情况BufferedReaderScanner都存在问题(前者经常无法检测到新行,而后者经常会去除空格,例如,从org.json库导出的 JSON 字符串中)。还有其他可用的方法,但问题是它们仅在某些 Java 版本之后才受支持(例如,这对 Android 开发人员不利),并且您可能不想仅出于这样的单一目的使用 Guava 或 Apache 公共库。因此,我的解决方案是将整个文件读取为字节并将其转换为字符串。下面的代码取自我的一个爱好项目:

    /**
     * Get byte array from an InputStream most efficiently.
     * Taken from sun.misc.IOUtils
     * @param is InputStream
     * @param length Length of the buffer, -1 to read the whole stream
     * @param readAll Whether to read the whole stream
     * @return Desired byte array
     * @throws IOException If maximum capacity exceeded.
     */
    public static byte[] readFully(InputStream is, int length, boolean readAll)
            throws IOException {
        byte[] output = {};
        if (length == -1) length = Integer.MAX_VALUE;
        int pos = 0;
        while (pos < length) {
            int bytesToRead;
            if (pos >= output.length) {
                bytesToRead = Math.min(length - pos, output.length + 1024);
                if (output.length < pos + bytesToRead) {
                    output = Arrays.copyOf(output, pos + bytesToRead);
                }
            } else {
                bytesToRead = output.length - pos;
            }
            int cc = is.read(output, pos, bytesToRead);
            if (cc < 0) {
                if (readAll && length != Integer.MAX_VALUE) {
                    throw new EOFException("Detect premature EOF");
                } else {
                    if (output.length != pos) {
                        output = Arrays.copyOf(output, pos);
                    }
                    break;
                }
            }
            pos += cc;
        }
        return output;
    }

    /**
     * Read the full content of a file.
     * @param file The file to be read
     * @param emptyValue Empty value if no content has found
     * @return File content as string
     */
    @NonNull
    public static String getFileContent(@NonNull File file, @NonNull String emptyValue) {
        if (file.isDirectory()) return emptyValue;
        try {
            return new String(readFully(new FileInputStream(file), -1, true), Charset.defaultCharset());
        } catch (IOException e) {
            e.printStackTrace();
            return emptyValue;
        }
    }

您可以简单地使用getFileContent(file, "")来读取文件的内容。

于 2020-08-07T07:41:56.527 回答