Geek Stocks
Geek Stocks

Reputation: 2030

How does one include a file of SQL statements internally in Java JAR?

I am trying to implement a variant of this SO question

I want to run tens of SQL statements against a database. Building the statements up in Strings is getting laborious. I got the idea to make a file of them instead (statements.sql) which is super easy to write and debug.

However I have a requirement that I must have everything needed contained in a runnable JAR, so this .sql file is going to have to be an internal resource (like C# projects). I cannot simply read an external file.

The SO question above sounds like the right idea for what I want, but no matter where I place the .sql file (src package, or a folder by itself), or if I "Add to Build Path" or not, I keep getting...

java.lang.NullPointerException

...when I run this code...

InputStream input = getClass().getResourceAsStream("/MySQL/src/com/package/statements.sql");

My Java IDE is Eclipse (Luna), running on Debian 7 GNome and the .sql file is currently in a package under source.

I just need the file's contents in a big string for parsing / processing. If there is a better way to do that I'd appreciate a push in the right direction. I think my issue may have more to do with my unfamiliarity with how to do this in Eclipse as opposed to code issue(s). To get the "path" string for the code I am right-clicking the .sql file and selecting "properties". The Path to the file (relative to the project?) is displayed there and I am copy / pasting that.

What is the right way to register this file with Eclipse and consume it? Thanks kindly.

Upvotes: 3

Views: 2008

Answers (1)

Arturo Volpe
Arturo Volpe

Reputation: 3627

From this answers

The path either has to be relative to the given class but without navigating back up the tree, or it has to be absolute to start with.

So you have two options:

  • Put the file in the same location of the class and get the file with getClass().getResourceAsStream("statements.sql")
  • Put the file in the root and get it with getClass().getResourceAsStream("\statements.sql") or getClass().getClassLoader().getResourceAsStream("statements.sql")

Upvotes: 1

Related Questions