Friday, July 6, 2007

HOWTO: load a file from a JAR into a String using JAVA

Overview
In some cases, a SQL creation script may be embedded in a jar. The following will show how to load this file into a usable object (String) for later passing to JDBC.

Technique
The idea is simple. Pass the path to the SQL script following the file structure of the JAR. In this example, "/derbyfun/sql/create.sql" is the file that is being extracted.

To get the contents of the file, the resource is opened as a stream and wrapped as a BufferedReader. The stream is then read, line by line, until end of file. For each line, the text is appended to a StringBuilder. At the end of the method, the StringBuilder is turned back into a string where it can be used in a JDBC call.
public String getResourceFileAsString(String resourcefilename) {
final String newline = System.getProperty("line.separator");
String line = null;
URL url = null;
BufferedReader b = null;
StringBuilder sb = new StringBuilder();
int i = 0;

try {
//
// open buffered reader
//
b = new BufferedReader(
new InputStreamReader(
Main.class.getResourceAsStream(resourcefilename)
)
);

//
// priming read and the loop through rest of file
//
line = b.readLine();
while(line != null) {
//
// add the line to the Stirng Builder ensuring
// the newline is re-added
//
sb.append(line + newline);
//
// just some debug
//
System.out.println("DEBUG: [" + ++i + "] " + line);

//
// read the next line
//
line = b.readLine();
} // end-while

} catch(Exception ex) {
ex.printStackTrace();
} // end-try-catch

return(sb.toString());
}


When the file is ready to be loaded, the following call can be used. In this example, the output is going to standard out. The file is in a sub package called sql which is part of "derbyfun".
System.out.println(
getResourceFileAsString("/derbyfun/sql/create.sql")
);


Final Thoughts
This is pretty straight forward code but may come in handy as a cut/paste for someone who does not remember the syntax... like me.