Alex Belke
Alex Belke

Reputation: 2233

how to create file in java in resources directory

I have a maven project and need to write JSON objects in file.json that should be located in

src/main/resources/

But before I need to check if file exists. If not than create it.

public static void writeMenuJSon(String jsonParamIn) {
    JsonParser parser = new JsonParser();
    JsonObject modulJson = parser.parse(jsonParamIn).getAsJsonObject();

    //TODO check if file exists and create file if not

   code here ...


   // write to file JSON object
   try (Writer writer = new FileWriter("path to file")){

        Gson gson = new GsonBuilder().create();
        gson.toJson(modulJson, writer);

    } catch (IOException e) {
        e.printStackTrace();
    }

}

Upvotes: 2

Views: 9169

Answers (2)

pirho
pirho

Reputation: 12215

What are you exactly trying to achieve writing the JSON file to the mentioned directory ?

I might miss something important in your question but:

it is possible to create code that does this thing but i'm not sure at all how are you going to run this code and is it sane solution to your problem?

When you mvn package the project name P having this "src/main/resources/" resources there will be added to package P.war/.jar or so but there will not be any JSON-file in directory until you run the code - this code you are after - that generates it and it is not done without some -maybe ugly- extra job.

If you have this code included in this project it will be run only when the project package is run. And there will not be this "src/main/resources/" where to write it.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240900

Something is totally wrong if you are creating dynamically file in src/main/resources This is only going to work in your development environment. When you deploy your code using Jar or War there won't be this directory on file system. It will be contained within Jar / War or other packaging.

If you understand above and still want to do it. Go related to your current working directory to create file, Usually the working directory when you launch your Main from IDE is setup to root of project so create a file at

src/main/resources/foo.txt

will do it. Alternatively you can figure out your current working directory from your IDE launcher or at runtime using

System.getProperty("user.dir");

Upvotes: 3

Related Questions