使用大多数相同的方法:
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
String(byte[])
构造函数将使用系统的默认编码,这肯定不是嵌入在Java应用程序中的资源的正确选择。应用程序应明确指定资源的编码。 - Holger您需要像我下面的代码片段一样将完整路径作为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
以下代码片段应该适合您使用。
Path path = Paths.get(CustomerControllerIT.class.getClassLoader().getResource(fileName).toURI());
byte[] fileBytes = Files.readAllBytes(path);
String fileContent = new String(fileBytes);
src/.../controllers/CustomerOrganization.json
。 - Michał KrzywańskiCustomerControllerIT.class.getResource("CustomerOrganization.json")
。 - Jonas Berlin