I am having a lot of headache with creating .jar that loads resources. I read a lot of posts here, but I don't have an idea how should I use
this.getClass().getResourceAsStream("..");
I need to load database into the memory:
File file = new File(Thread.currentThread().
getContextClassLoader().getResource("phonebook").getFile());
String attachStmt = "ATTACH '" + file + "' AS tempInMemoryDb";
stmt.execute(attachStmt);
So if I run project from NetBeans it loads database just fine, but when I do clean and build, and run jar file from dis folder I see in command line that phonebook file (database file) isn't loaded. So, my question is: how should I use this.getClass().getResourceAsStream("..")
to create file and pass it to "String attachStmt = "ATTACH '" + file + "' AS tempInMemoryDb";
so I can load DB?
ATTACH
expects a file as input, but when you build a JAR for your application, the file you are referring to is inside this JAR and not extracted! In this case, you need to write the data to a file first.
Create an empty temporary file by calling File.createTemporaryFile
. The use one of the methods described in the answers to this question to copy the content of the stream returned from getResourceAsStream
into the temporary file.
When you program exits, don't forget to delete the temporary file. One way to ensure that is to call deleteOnExit
on the temporary file object returned in the first step.