Importing json file

Hi I have to integrate some code from someone else and in his code he loads a file with the “File” class. The file itself can be found in the project assets. Though I fail to load the file with a relative path. I know this is not best practice and there are much better ways of doing this, but I have to integrate the code.

It works with a fixed path, though it has to become relative:

[java] File f = new File(“C:/Users/user1/Documents/MyGame/trunk/sandbox/assets/info.json”);
byte[] fileinbytes = Files.readAllBytes(Paths.get(f.toURI()));[/java]

Anyone can provide some help ?

I suggest adding the json file to the assets folder and loading it via a classpath loader, the path will always be different depending on how the application is being run. Something like myClass.getClassLoader().getResourceAsStream(“info.json”) This will then also work on android and iOS for example.

1 Like

@norman, thx for the answer, but I can’t read it as a stream. But based on your suggestion I wrote this code:
String path = this.getClass().getClassLoader().getResource(“info.json”).getPath();
File f = new File(path);[/java]

In the IDE it works, though when using a stand-alone exe, I get an error:

InvalidPathException: Illegal char <:> at index 45: C:/Users/user1/Desktop/MyGame-Windows/file:/C:/Users/user1/Desktop/MyGame-Windows/lib/assets.jar!/info.json"

So it seems that the path its being executed in is being concatinated to the path where the json file is.

Any idea how to avoid this?

I don’t think it is possible to use “File” for loading resources inside zip/jar-files.

Yeah, I should probably have said it explicitly, I thought it was clear from the context: Don’t use File.

Reading as an inpustream seems to work. For my purposes I had to transform this inputstream to a byte array. But this solution seems to work.