1

I'm trying to save a HashMap as a JSON file using Jackson. I want said file to be located in my resources folder.

try {
        new ObjectMapper().writeValue(
                new File(MyClass.class.getResource("/path/file.json").toURI()), myHashMap);
    } catch (URISyntaxException | IOException e) {
        e.printStackTrace();
    }

I've tried this approach, which yields no Exceptions, but leaves me with a blank JSON file. No data gets written into it. Is this some permissions problem?

Also I want to read this file as a HashMap. This is my current approach:

Map<Long, String> tmp;
    try {
        tmp = new ObjectMapper().readValue(
                MyClass.class.getResourceAsStream("/path/file.json"), Map.class);
    } catch (IOException e) {
        tmp = new HashMap<>();
    }
    myHashMap = tmp;

Are there any better ways to do so? To my understanding the exception is normally thrown when the file could not be found (Leaving actual errors out of the equation). Which is alright, just go with an empty HashMap instead then. Since it will get populated later on and saved, so this case only exists when starting the program for the first time or when the file gets deleted.

Right now I'm mostly having trouble saving my file.

moeux
  • 191
  • 15
  • 3
    Resources are read-only. If you need to read and write information, you will need to use an external file instead. – DontKnowMuchBut Getting Better Dec 27 '20 at 17:44
  • @DontKnowMuchButGettingBetter is it possible to replace the file then? So every time I want to save the file I just create a new one under resources and delete the old one. – moeux Dec 27 '20 at 20:41
  • 1
    There are kludges that might allow this, but I strongly urge you to not consider this route. Instead if there are program properties that need to be written to, keep them out of the jar file. The initial values can be held by the jar file, fine, but if something later needs updating, it should be stored out of the jar. – DontKnowMuchBut Getting Better Dec 27 '20 at 21:40
  • @DontKnowMuchButGettingBetter I understand, I'll keep the file somewhere else then. Thank you! – moeux Dec 27 '20 at 22:27
  • 1
    Do not attempt to write a resource. Treat the resource as your *default data,* while defining a known file path (such as something in the directory named by `System.getProperty("user.home")`) where your program writes modifications. Always write to that location. When reading, if that file exists, read it; if it doesn't exist, fall back on reading your resource. – VGR Dec 28 '20 at 04:37

0 Answers0