Get SQL Statements from a File
Return a List containing all SQL Statements in a specified File.
Javadoc available at https://www.javatapas.com/docs/javatapas/sql/GetSqlStatementsFromFile.html
public static List<String> getSqlStatementsFromFile(String fileName) throws IOException {
List<String> statements = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
StringBuilder sb = new StringBuilder();
boolean insideComment = false;
boolean lastLineEndedComment = false;
while (line != null) {
line = line.trim();
if (insideComment && lastLineEndedComment){insideComment = false;}
if (line.startsWith("/*")){insideComment = true;}
if (insideComment && line.endsWith("*/")){lastLineEndedComment = true;}
if (!insideComment && !line.trim().startsWith("--")){
sb.append(line);
if (line.endsWith(";")){
statements.add(sb.toString());
sb = new StringBuilder();
}
else {sb.append(" " );}
}
line = reader.readLine();
}
// check the last StringBuilder to see if it looks like a legit sql statement b/c the last statement does not need to end with a semicolon
String lastStatement = sb.toString();
if (lastStatement.trim().length() > 0){statements.add(lastStatement);}
reader.close();
return statements;
}