Reputation: 630
I have a Java-only module in my Android project. In that project I want to have a unit test that reads the contents from a local json file that is stored in the resources folder. Android Studio changes the icon of the resources folder, so I'd think it recognises it as the resources folder.
How I'm reading:
String json = Files.lines(Paths.get("file.json"))
.parallel()
.collect(Collectors.joining());
folder structure:
+project
+app (android)
+module (java only)
+src
+main
+java
+package
-the java file
+resources
-file.json
My question is how can I read the file?
updated below
URL resource1 = getClass().getResource("file.json");
URL resource2 = getClass().getClassLoader().getResource("file.json");
URL resource3 = Thread.currentThread().getContextClassLoader().getResource("file.json");
URL resource4 = ClassLoader.getSystemClassLoader().getResource("file.json");
All these are null.
I've copied the json file to resources/same.package.structure
too, but to no success.
Upvotes: 6
Views: 19048
Reputation: 630
Apparently it was a bug, should be fixed now: https://issuetracker.google.com/issues/63612779
Thank you all for your help
Upvotes: -1
Reputation: 2764
Don't need to do all this complicated stuff with ClassLoaders. You have access to test/resources directory from you /test/* classes.
UPD This is how to deserialize file using its path using SimpleXML. So here source method param is your path to resource file
Upvotes: 7
Reputation: 30676
you should using Paths.get(URI)
instead, for example:
ClassLoader loader = ClassLoader.getSystemClassLoader();
String json = Files.lines(Paths.get(loader.getResource("file.json").toURI()))
.parallel()
.collect(Collectors.joining());
this is because you run your tests in android platform, and the resoruces were packaged in a jar, please using BufferedReader.lines
instead, for example:
ClassLoader loader = activity.getClassLoader();
BufferedReader in = new BufferedReader(new InputStreamReader(
loader.getResourceAsStream("file.json"),"UTF-8"
));
String json = in.lines()
.parallel()
.collect(Collectors.joining());
Upvotes: 3