Java 8:将文件读入字符串

6

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

new String(Files.readAllBytes(Paths.get("CustomerOrganization.json")));

但是我遇到了一个错误:

java.nio.file.NoSuchFileException: CustomerOrganization.json

enter image description here


你必须提供完整的路径。那个文件在你的文件系统中的哪里存储? - deHaar
路径不是相对于你的类所在的位置,而是相对于程序运行的位置。通常这是项目的根目录。 - Jonas Berlin
你也可以尝试从项目根目录开始给出相对路径,例如 src/.../controllers/CustomerOrganization.json - Michał Krzywański
如果您想相对于您的类找到文件的路径,可以使用CustomerControllerIT.class.getResource("CustomerOrganization.json") - Jonas Berlin
如果您希望在同一软件包中使用它,您应该使用资源而不是文件。 - RealSkeptic
我建议在 "new String(...)" 调用中添加一个编码参数,以确保它使用正确的编码读取文件。 - Jonas Berlin
3个回答

13

使用大多数相同的方法:

new String(Files.readAllBytes(Paths.get(CustomerControllerIT.class.getResource("CustomerOrganization.json").toURI())));

然而,如果您需要从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://dev59.com/UHVC5IYBdhLWcg3wZwJT#35446009

真的,但这不是问题中要求的。 - Jonas Berlin
3
然而,如果OP要部署它,它将最终被打包成一个Jar文件。任何涉及资源的解决方案都不应该混合在文件中,因为项目几乎永远不会以文件形式部署。 - RealSkeptic
已完成,同时添加了JAR解决方案。 - Jonas Berlin
2
URI的绕路甚至可以在从jar创建文件系统时使用,但必须强调String(byte[])构造函数将使用系统的默认编码,这肯定不是嵌入在Java应用程序中的资源的正确选择。应用程序应明确指定资源的编码。 - Holger
编码方面怎么样? - AlikElzin-kilaka
@AlikElzin-kilaka,您是在指回答还是Holger的评论? - Jonas Berlin

4

您需要像我下面的代码片段一样将完整路径作为URI提供,其中json文件位于同一个包中。

try {
        String s = new String(Files.readAllBytes(Paths.get("D:/Test/NTech/src/com/ntech/CustomerOrganization.json")));
        System.out.println(s);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

如需更多信息,请查看Paths类的public static Path get(URI uri)方法文档,链接为:https://docs.oracle.com/javase/8/docs/api/java/nio/file/Paths.html


2
以下代码片段应该适合您使用。

以下代码片段应该适合您使用。

Path path = Paths.get(CustomerControllerIT.class.getClassLoader().getResource(fileName).toURI());
byte[] fileBytes = Files.readAllBytes(path);
String fileContent = new String(fileBytes);

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