How do I check whether a SQLite database file exists using Java?
public static void databaseConnect(String dbName) throws Exception {
File file = new File (dbName);
if(file.exists()) //here's how to check
{
System.out.print("This database name already exists");
}
else{
Class.forName("SQLite.JDBCDriver").newInstance();
conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
stat = conn.createStatement();
}
Assuming that your dbName
parameter indicates the path to the SQLite file ("-wal" and "-shm" companion files notwithstanding), you can use the Java java.io.File
class and its exists()
predicate:
final File f = new File(dbName);
if (f.exists())
{
if (f.isDirectory())
{
// Warn about the designated name being a directory.
}
else
{
// Warn about the designated name already existing as a file.
}
}
Other checks could be warranted too, such as whether the process has the privilege to create the file, though ultimately SQLite will do a better job ensuring that all its requirements can be fulfilled.