Java 8:将文件读入字符串

San*_*Rey 4 java file-io file java-8

我在控制器的同一个包中有一个 json 文件,我尝试读取该文件并将其转换为 String

new String(Files.readAllBytes(Paths.get("CustomerOrganization.json")));
Run Code Online (Sandbox Code Playgroud)

但我得到了一个错误:

java.nio.file.NoSuchFileException: CustomerOrganization.json
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Jon*_*lin 10

使用与您使用的方法大致相同的方法:

new String(Files.readAllBytes(Paths.get(CustomerControllerIT.class.getResource("CustomerOrganization.json").toURI())));
Run Code Online (Sandbox Code Playgroud)

但是,如果您需要它在 JAR 中工作,则需要这样做:

InputStream inputStream = CustomerControllerIT.class.getResourceAsStream("CustomerOrganization.json");
// TODO pick one of the solutions from below url
// to read the inputStream into a string:
// https://stackoverflow.com/a/35446009/1356047
Run Code Online (Sandbox Code Playgroud)

  • 然而,如果 OP 要部署它,它最终会被放在一个 Jar 中。任何涉及资源的解决方案都不应该混合在文件中,因为项目几乎永远不会最终部署为文件。 (3认同)
  • 当您首先创建文件系统时,URI 绕行甚至可以在 jar 中工作。但必须强调的是,“String(byte[])”构造函数将使用系统的默认编码,这对于嵌入在 Java 应用程序中的资源来说肯定不是正确的选择。应用程序应该明确资源的编码。 (2认同)