Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 851
Sandro Rey Avatar asked Jul 24 '19 07:07

Sandro Rey


People also ask

How do you read a text file as a String in Java?

The readString() method of File Class in Java is used to read contents to the specified file. Return Value: This method returns the content of the file in String format. Note: File. readString() method was introduced in Java 11 and this method is used to read a file's content into String.

What is the easiest way to read text files line by line in Java 8?

Java 8 has added a new method called lines() in the Files class which can be used to read a file line by line in Java. The beauty of this method is that it reads all lines from a file as Stream of String, which is populated lazily as the stream is consumed.

How do I create a Java String from the contents of a file?

String content = new String(Files. readAllBytes(Paths. get(filename)), "UTF-8"); Since Java 7, the JDK has the new java.


2 Answers

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
like image 109
Jonas Berlin Avatar answered Oct 29 '22 05:10

Jonas Berlin


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

like image 23
Sukriti Sarkar Avatar answered Oct 29 '22 04:10

Sukriti Sarkar