Java 将文件读入字符串的最简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3402735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:58:16  来源:igfitidea点击:

What is simplest way to read a file into String?

javafilefile-io

提问by Gopi

I am trying to read a simple text file into a String. Of course there is the usual way of getting the input stream and iterating with readLine() and reading contents into String.

我正在尝试将一个简单的文本文件读入一个字符串。当然,有获取输入流并使用 readLine() 进行迭代并将内容读入 String 的常用方法。

Having done this hundreds of times in past, I just wondered how can I do this in minimum lines of code? Isn't there something in java like String fileContents = XXX.readFile(myFile/*File*/).. rather anything that looks as simple as this?

过去已经这样做了数百次,我只是想知道如何以最少的代码行做到这一点?java 中难道没有类似String fileContents = XXX.readFile(myFile/*File*/).. 的东西,而是看起来像这样简单的东西吗?

I know there are libraries like Apache Commons IO which provide such simplifications or even I can write a simple Util class to do this. But all that I wonder is - this is a so frequent operation that everyone needs then why doesn't Java provide such simple function? Isn't there really a single method somewhere to read a file into string with some default or specified encoding?

我知道有像 Apache Commons IO 这样的库提供了这样的简化,甚至我可以编写一个简单的 Util 类来做到这一点。但我想知道的是 - 这是每个人都需要的如此频繁的操作,那么为什么 Java 不提供如此简单的功能呢?在某处真的没有一种方法可以将文件读入具有某种默认或指定编码的字符串吗?

采纳答案by polygenelubricants

Yes, you can do this in one line (though for robust IOExceptionhandling you wouldn't want to).

是的,您可以在一行中完成此IOException操作(尽管对于强大的处理,您不希望这样做)。

String content = new Scanner(new File("filename")).useDelimiter("\Z").next();
System.out.println(content);

This uses a java.util.Scanner, telling it to delimit the input with \Z, which is the end of the string anchor. This ultimately makes the input have one actual token, which is the entire file, so it can be read with one call to next().

这使用 a java.util.Scanner,告诉它用 分隔输入\Z,这是字符串锚点的结尾。这最终使输入具有一个实际标记,即整个文件,因此可以通过调用next().

There is a constructorthat takes a Fileand a String charSetName(among many other overloads). These two constructor may throw FileNotFoundException, but like all Scannermethods, no IOExceptioncan be thrown beyond these constructors.

一个带有aFile和 a的构造函数String charSetName(在许多其他重载中)。这两个构造函数可能会 throw FileNotFoundException,但与所有Scanner方法一样,IOException除了这些构造函数之外,不能抛出任何内容。

You can query the Scanneritself through the ioException()method if an IOExceptionoccurred or not. You may also want to explicitly close()the Scannerafter you read the content, so perhaps storing the Scannerreference in a local variable is best.

如果发生与否,您可以Scanner通过该ioException()方法查询自身IOException。您可能还需要明确close()Scanner后您阅读的内容,因此,或许存储Scanner在一个局部变量的引用最好。

See also

也可以看看

Related questions

相关问题



Third-party library options

第三方库选项

For completeness, these are some really good options if you have these very reputable and highly useful third party libraries:

为完整起见,如果您拥有这些信誉良好且非常有用的第三方库,这些是一些非常好的选择:

Guava

番石榴

com.google.common.io.Filescontains many useful methods. The pertinent ones here are:

com.google.common.io.Files包含许多有用的方法。这里的相关内容是:

Apache Commons/IO

Apache Commons/IO

org.apache.commons.io.IOUtilsalso offer similar functionality:

org.apache.commons.io.IOUtils还提供类似的功能:

  • String toString(InputStream, String encoding)
    • Using the specified character encoding, gets the contents of an InputStreamas a String
  • List readLines(InputStream, String encoding)
    • ... as a (raw) Listof String, one entry per line
  • String toString(InputStream, String encoding)
    • 使用指定的字符编码,获取 a 的内容InputStream作为 aString
  • List readLines(InputStream, String encoding)
    • ... 作为(原始)Listof String,每行一个条目

Related questions

相关问题

回答by Nikita Rybak

Sadly, no.

可悲的是没有。

I agree that such frequent operation should have easier implementation than copying of input line by line in loop, but you'll have to either write helper method or use external library.

我同意这种频繁的操作应该比在循环中逐行复制输入更容易实现,但是您必须编写辅助方法或使用外部库。

回答by Jon Skeet

Don't write your own util class to do this - I would recommend using Guava, which is full of all kinds of goodness. In this case you'd want either the Filesclass (if you're really just reading a file) or CharStreamsfor more general purpose reading. It has methods to read the data into a list of strings (readLines) or totally (toString).

不要编写自己的 util 类来执行此操作 - 我建议使用Guava,它充满了各种优点。在这种情况下,您需要Files类(如果您真的只是阅读文件)或CharStreams以进行更通用的阅读。它具有将数据读入字符串列表 ( readLines) 或完全 ( toString) 的方法。

It has similar useful methods for binary data too. And then there's the rest of the library...

它对二进制数据也有类似的有用方法。然后是图书馆的其余部分......

I agree it's annoying that there's nothing similar in the standard libraries. Heck, just being able to supply a CharSetto a FileReaderwould make life a littlesimpler...

我同意标准库中没有类似的东西很烦人。哎呀,仅仅能够提供 aCharSet到 aFileReader会让生活变得更简单......

回答by Bhuvan Gupta

Another alternative approach is:

另一种替代方法是:

How do I create a Java string from the contents of a file?

如何从文件的内容创建 Java 字符串?

Other option is to use utilities provided open source libraries
http://commons.apache.org/io/api-1.4/index.html?org/apache/commons/io/IOUtils.html

其他选项是使用提供的开源库的实用程序
http://commons.apache.org/io/api-1.4/index.html?org/apache/commons/io/IOUtils.html

Why java doesn't provide such a common util API ?
a)to keep the APIs generic so that encoding, buffering etc is handled by the programmer.
b)make programmers do some work and write/share opensource util libraries :D ;-)

为什么java不提供这样一个通用的util API?
a)保持 API 的通用性,以便程序员处理编码、缓冲等。
b)让程序员做一些工作并编写/共享开源实用程序库 :D ;-)

回答by Rakesh Goyal

You can use apache commons IO..

您可以使用 apache commons IO ..

FileInputStream fisTargetFile = new FileInputStream(new File("test.txt"));

String targetFileStr = IOUtils.toString(fisTargetFile, "UTF-8");

回答by Jim

From Java 7 (API Description)onwards you can do:

从 Java 7 (API 描述)开始,您可以执行以下操作:

new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

Where filePath is a String representing the file you want to load.

其中 filePath 是一个字符串,表示您要加载的文件。

回答by wvdz

I discovered that the accepted answer actually doesn't always work, because \\Zmay occur in the file. Another problem is that if you don't have the correct charset a whole bunch of unexpected things may happen which may cause the scanner to read only a part of the file.

我发现接受的答案实际上并不总是有效,因为\\Z可能出现在文件中。另一个问题是,如果您没有正确的字符集,可能会发生一大堆意想不到的事情,这可能会导致扫描仪只读取文件的一部分。

The solution is to use a delimiter which you are certain will never occur in the file. However, this is theoretically impossible. What we CAN do, is use a delimiter that has such a small chance to occur in the file that it is negligible: such a delimiter is a UUID, which is natively supported in Java.

解决方案是使用您确定不会在文件中出现的分隔符。然而,这在理论上是不可能的。我们可以做的是使用一个分隔符,它在文件中出现的几率很小,可以忽略不计:这样的分隔符是一个UUID,Java 原生支持它。

String content = new Scanner(file, "UTF-8")
    .useDelimiter(UUID.randomUUID().toString()).next();

回答by DDas

This should work for you:

这应该适合你:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public static void main(String[] args) throws IOException {
    String content = new String(Files.readAllBytes(Paths.get("abc.java")));
}

回答by cjungel

Using Apache Commons IO.

使用Apache Commons IO

import org.apache.commons.io.FileUtils;

//...

String contents = FileUtils.readFileToString(new File("/path/to/the/file"), "UTF-8")

You can see de javadoc for the methodfor details.

您可以查看 de javadoc 了解该方法的详细信息。