对Windows计算机上的Derby Embedded数据库调用shutdown = true时,我无法删除系统目录 。
这是我的挑战的一个最简单的例子:
package derbytest; import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author aelder */ public class DerbyTest { private static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver"; private static final String CONN_URL = "jdbc:derby:EmbeddedDBAudit"; private static File derbySystemFolder; private static final String USER_HOME_DIR = System.getProperty("user.home", "."); public static Connection getConnection(boolean createDatabase) throws SQLException { return DriverManager.getConnection(CONN_URL + (createDatabase ? ";create=true" : "")); } public static void shutdownConnectionAndCleanup() { try { DriverManager.getConnection(CONN_URL + ";shutdown=true"); } catch (SQLException ex) { if (!ex.getSQLState().equals("08006")) { ex.printStackTrace(); } } deleteFolder(derbySystemFolder); } public static void deleteFolder(File folder) { File[] files = folder.listFiles(); if (files != null) { //some JVMs return null for empty dirs for (File f : files) { if (f.isDirectory()) { deleteFolder(f); } else { f.delete(); } } } folder.delete(); } public static void setDerbyHome() { setDatabaseFile(""); int index = 1; while (derbySystemFolder.exists()) { setDatabaseFile(String.valueOf(index++)); } // Set the db system directory. System.setProperty("derby.system.home", derbySystemFolder.getAbsolutePath()); } private static void setDatabaseFile(String auditFolderCount) { String databaseFilePATH = USER_HOME_DIR + File.separator + ".EmbeddedDBAudit" + auditFolderCount; derbySystemFolder = new File(databaseFilePATH); derbySystemFolder.deleteOnExit(); } public static void initDerbyHomeAndDriver() { setDerbyHome(); initDerbyDriverInstance(); } public static void initDerbyDriverInstance() { try { Class.forName(DRIVER).newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { Logger.getLogger(DerbyTest.class.getName()).log(Level.SEVERE, null, ex); } } public static boolean tableAlreadyExists(SQLException e) { return e.getSQLState().equals("X0Y32"); } /** * @param args the command line arguments */ public static void main(String[] args) { try { initDerbyHomeAndDriver(); getConnection(true); shutdownConnectionAndCleanup(); } catch (SQLException ex) { Logger.getLogger(DerbyTest.class.getName()).log(Level.SEVERE, null, ex); } } }
我已经尝试使用外部库删除文件夹以及如apache的org.apache.commons.io.FileDeleteStrategy.FORCE.delete(file);
或者import org.apache.commons.io.FileUtils.deleteDirectory(file);
。 即使在数据库closures后,似乎derby系统仍然挂在文件上。
期望的行为:在退出时删除系统目录 。