Java8:将文件读入字符串

Java 8: Reading a file into a String

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

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

但是我得到一个错误:

java.nio.file.NoSuchFileException: CustomerOrganization.json

主要使用与您使用的方法相同的方法:

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:
// 

你必须像我下面的代码片段一样提供完整路径作为 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 class 的 public static Path get(URI uri) 方法文档,来自:https://docs.oracle.com/javase/8/docs/api/java/nio/file/Paths.html

下面的代码片段应该适合您。

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