I'm trying to load properties, and if it is not exist to create one.
ok, here is loading:
InputStream is = Store.class.getResourceAsStream("my.properties");
props.load(is);
but the hard part is to determinate if file not exist and create it if necessary
tried this one:
File conf = null;
try {
conf = new File(Store.class.getResource("my.properties").getFile());
}
catch (Exception e){
// can't create file because getResource returns null again
conf = new File(Store.class.getResource("my.properties").getFile()); //WRONG
conf.createNewFile();
}
what I can do in this case?
Actually if the file does not exist, the getResource method will return null, so you will get a NullPointerException both inside try and inside catch blocks.
I don't know actually whether it is anyway possible to create the desired file, because at first you need its complete path, which you cannot get because the method getResource or getResourceAsStream will return null.
What you can do is to get the path of another resource file that already exists inside the same folder and use it to get the path of the parent folder then add the desired file name to it.
final File myfile = new File(new File(BooleanFact.class.getResource("existingfile").getFile()).getParentFile(), "myfile");
myfile.createNewFile();
But you should notice that project resources are not actually intended to be created at runtime. They should be added at development-time and usually only read (not modified). If you need some files to update at runtime, you should use the normal file system.
getResource and getResourceAsStream can load a resource from any place in your classpath. You should not assume it is even a file in the filesystem, as it can be inside a .jar file. Therefore you should not try to create the file if it is missing.
Instead if you want to load the file from a file system, you should know the location where you want to load it from. You can also consider a hybrid approach where you first try to load it from a resource, and if it is not found, then load from a specific place in file system and create the file if it is missing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With