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]
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.
@norman, thx for the answer, but I can’t read it as a stream. But based on your suggestion I wrote this code:
[java]
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.