Home > Enterprise >  How do I write a JSON file using GSON in the resources folder without using src/main/resources?
How do I write a JSON file using GSON in the resources folder without using src/main/resources?

Time:05-23

I'm trying to write a JSON file with GSON in the resources folder without using src/main/resources:

package repository;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.tinylog.Logger;

import java.io.*;
import java.util.List;

public class GsonRepository<T> extends Repository<T> {

    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();

    public GsonRepository(Class<T> elementType) {
        super(elementType);
    }

    public void saveToFile(String resourceName) throws IOException {
        try (var writer = new FileWriter(this.getClass().getResource(resourceName).getPath())) {
            GSON.toJson(elements, writer);
        }
    }
}

This doesn't seem to be working. What am I doing wrong?

CodePudding user response:

I'm trying to write a JSON file with GSON in the resources folder

Well, that's your problem. Because that's completely impossible.

The 'resources' folder is a thing that exists on the computer of the developer only. Hence, you can't write to a thing that doesn't exist.

The resources folder is solely for read-only resources. Think files of tabular data (say, a list of country names and phone number prefixes), icon files, HTML templates, that sort of business.

You can only load these files with GsonRepository.class.getResource and (.getResourceAsStream) - any attempt to treat them as files will work during dev and then fail when you deploy.

If you have config files or save files, these don't go in the resources folder, aren't loaded with .getResource at all. You should place these in the user's home dir (System.getProperty("user.home")): The directory where the java app is installed will not be writable by the app itself (or if it is, you have a pretty badly configured OS for security purposes. Windows is, of course, badly configured. That doesn't make it a good idea to start sticking user-editable data files in the install dir of the app, though!)

new FileWriter(this.getClass().getResource

this doesn't make sense. In java, File means file. And a resource is not a file - for example, an entry in a jar file is not a file. But, resources tend to be entries in jar files.

Note that it's YourClass.class.getResource, not .getClass().getResource - the latter can break when you subclass, the former never breaks and is therefore superior in every way. When there are 2 ways to do a thing that are virtually identical in readability, and one is applicable to strictly more scenarios than the other, then never use the other.

  • Related