如何在Java中获取文件内容?

44

通常我使用扫描器并迭代每一行来获取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"))
6个回答

36

虽然没有内置的API,但是Guava库提供了这个功能。它是一个非常好用的库。

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

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

请注意,此方法现已过时。其新的等效方法是:

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

1
Files#toString已被弃用。文档说明:建议使用{@code asCharSource(file, charset).read()}。该方法将在2019年1月被删除。 - Stephan

28

链接似乎已经失效。 - Korhan Ozturk
已更新,链接已修复。 - rich
9
很酷,你也可以使用readAllBytes()并做出以下一行式样的代码,而不需要任何第三方库:String content = new String(Files.readAllBytes(new File("/my/file.txt")).toPath())。 - KIC

20

commons-io有以下功能:

IOUtils.toString(new FileReader("file.txt"), "utf-8");

16

1
Java 11中的Files.readString()使得读取文件变得更加简单。 - tom

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
}

0
经过一些测试,我发现在各种情况下BufferedReaderScanner都存在问题(前者经常无法检测到新行,后者经常从由org.json库导出的JSON字符串中剥离空格)。虽然还有其他可用的方法,但问题是它们仅在某些Java版本之后受支持(例如对于Android开发人员来说很糟糕),而您可能不想仅仅为了这个目的使用Guava或Apache commons库。因此,我的解决方案是将整个文件读取为字节并将其转换为字符串。下面的代码摘自我的一个业余项目:
    /**
     * 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, "")来读取文件的内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接