0

I have to implement a temporary "persistence" solution for retrieving some definitions ( simple json strings). I have a rest endpoint which creates an instance of my object and then I want to write the json definition inside a file.

I currently have a class loader which loads files from the resources folder inside my module, I use these to grab the query results. Now I want to save a new definition, and write it to a file inside the resources folder.

However, I am unsuccessful in doing so. I grab the path from the existing file with the classloader and when I try to create a new file using FileUtils, it either throws some errors, or creates the file in D:.

Is there a way to use the resources folder to add/edit files at runtime ? Here is some code also with one of the many ways i've tried it.

public String writeDocument(String path, String content) throws IOException {

    \\Example call: writeDocument("/definitions/somedefinition.txt",jsonStringHere);
    \\where /definitions/somedefinition.txt is placed in /resources

    ClassLoader classLoader = getClass().getClassLoader();
    final URL url = classLoader.getResource(path);
    final File file;
    String finalPath = null;
    try {
        file = Paths.get(url.toURI()).toFile();
        FileUtils.writeStringToFile(file, content);
        finalPath = file.getAbsolutePath();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    return finalPath;
}
D.Razvan
  • 325
  • 1
  • 5
  • 18
  • How temporary is your temporary solution needs to be? – Aleksandr M Aug 18 '15 at 11:31
  • Probably till the end of the current sprint, or till the end of the month. Just needs to be as basic as can be, only working of course. – D.Razvan Aug 18 '15 at 11:46
  • Do yourself a favor and use some db. – Aleksandr M Aug 18 '15 at 11:50
  • I wish I could spare the resources now to implement it, but in the near future we will be required to use one, and there are some strict setup rules in place, which will require to replace it in full anyway. – D.Razvan Aug 18 '15 at 12:03
  • If it is that temporary, you might as well just use a hardcoded path and not try to use classpath resources. You should treat all classpath resources as read-only - because they might as well be inside a jar file and not directly on the local filesystem. EDIT: and by hardcoded path I mean probably a directory inside the user home folder. – Gimby Aug 18 '15 at 13:38
  • Yea Gimby, thats exactly what I was going to do right now. Seems like the only way for now, even though it's ugly. – D.Razvan Aug 18 '15 at 14:04
  • @D.Razvan I wouldn't limit yourself with such "ugliness" opinions, the most beautiful solutions are the ones that work reliably, you can understand and someone else can understand too. Using the user home directory is a lot cleaner than trying to write something on the classpath. – Gimby Aug 21 '15 at 07:26

0 Answers0