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
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.
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.
String content = new String(Files. readAllBytes(Paths. get(filename)), "UTF-8"); Since Java 7, the JDK has the new java.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With