How to check if SQLite database file exists using Java?

I get the database file name from the user and I want to check if this file exists. If it exists, I want to show the user an error message, but I do not know how to check if the file exists.

public static void databaseConnect(String dbName) throws Exception { if (/*same name exists*/) // How do I check this? { System.out.print("This database name already exists"); } else { Class.forName("SQLite.JDBCDriver").newInstance(); conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName); stat = conn.createStatement(); } } 
+6
source share
5 answers
 public static void databaseConnect(String dbName) throws Exception { File file = new File (dbName); if(file.exists()) //here 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(); } 
+13
source

Assuming your dbName parameter specifies the path to the SQLite files (only "-wal" and "-shm"), you can use the Java class java.io.File and the predicate exists() :

 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 can also be justified, for example, whether the process has the privilege to create a file, although in the end SQLite will work better by ensuring that all of its requirements can be met .

+3
source

I found that the best way to do this is to check the file size instead. If you do:

return new File(DB_NAME).exists() should be True.

You have to get a true back because it will create it. Instead, check that the file size is greater than 0. At least in this case, you know the data in the file without adding or requesting results.

Instead, run:

return new File(DB_NAME).length() > 0

+1
source

Something like that?

 public boolean databaseExist() { File dbFile = new File(DB_PATH + DB_NAME); return dbFile.exists(); } 
0
source

late can this help:

 public boolean didPackageCreate() { File dbfile = this.getDatabasePath("app.db"); if(dbfile.exists()){ // db exist }else{ // db doesn't exist } } 
0
source

Source: https://habr.com/ru/post/895289/


All Articles