Sandro Rey
Sandro Rey

Reputation: 2999

Java 8: Reading a file into a String

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

Upvotes: 10

Views: 27521

Answers (3)

Asim Irshad
Asim Irshad

Reputation: 96

Below code snippet should work for you.

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

Upvotes: 2

Jonas Berlin
Jonas Berlin

Reputation: 3482

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

Upvotes: 15

Sukriti Sarkar
Sukriti Sarkar

Reputation: 131

You have to give the full path as URI like my below code snippet where the json file is in the same package.

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();
    }

For more information you can go through the public static Path get(URI uri) method documentation of the Paths class from: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Paths.html

Upvotes: 4

Related Questions