Java 8: Reading a file into a String

Sandro Rey :

I have a json file in the same package of the controller, and I try to read the file and convert it into String

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

But I got an error:

java.nio.file.NoSuchFileException: CustomerOrganization.json

enter image description here

Jonas Berlin :

Using mostly the same methods you used:

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

However, if you need it to work from inside a JAR, you will need to do this instead:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327701&siteId=1