static boolean restoreStoreFrom(File from) { String path = context.getDatabasePath(DATABASE_NAME + ".restore").getPath(); File outDir = new File(path); if (!outDir.exists()) outDir.getParentFile().mkdirs(); FileOutputStream ksOut; try { ksOut = new FileOutputStream(outDir); } catch (FileNotFoundException e) { Log.e(TAG, "Cannot open restore temp file for key manager", e); return false; } FileInputStream ksIn; try { ksIn = new FileInputStream(from); } catch (FileNotFoundException e) { Log.e(TAG, "Cannot open backup file for restore operation", e); return false; } byte[] buffer = new byte[8 * 1024]; int read; try { while ((read = ksIn.read(buffer)) != -1) { ksOut.write(buffer, 0, read); } } catch (IOException e) { try { ksIn.close(); ksOut.close(); } catch (IOException e1) { outDir.delete(); // remove temp file in case of problems return false; } outDir.delete(); return false; } try { ksIn.close(); } catch (IOException ignore) { } try { ksOut.close(); // This may causes a IOEception "bad file number": ksOut.getFD().sync(); } catch (IOException e) { outDir.delete(); return false; } // At this point the restore temp file is ready, rename it to real store file if (!outDir.renameTo(context.getDatabasePath(DATABASE_NAME))) { Log.e(TAG, "Restore from backup file: rename to key store name failed"); return false; } return true; }
/** * 初始化目录 * * @param context 上下文 * @param currentUserId 当前用户ID */ public static void initDirs(Context context, String currentUserId) { sAppRootDirPath = context.getDir(ROOT_DIR_NAME, Context.MODE_PRIVATE).getAbsolutePath(); if (!TextUtils.isEmpty(currentUserId)) { sCurrentUserHomePath = sAppRootDirPath + File.separator + currentUserId; sCurrentUserConfigPath = sCurrentUserHomePath + File.separator + "config"; } sDatabasePath = context.getDatabasePath(sDatabaseName).getAbsolutePath(); sCurrentUserConfigPath = context.getDatabasePath("config").getAbsolutePath(); }
/** Copy all Assets by Type to the local storage returns boolean Uses by InitialActivity */ public static boolean copyAssets(Context context, String assetType, boolean rewrite) { Log.d(TAG, "copyAssets(), assetType=" + assetType); // Get asset manager and define list of files to copy AssetManager assetManager = context.getAssets(); String[] files = null; try { files = assetManager.list(assetType); } catch (IOException ioe) { // exit if something wrong with assets Log.d(TAG, "copyAssets(),Failed to get asset file list.", ioe); return false; } // copy files if exists for (String fileName : files) { InputStream in = null; OutputStream out = null; File outFile = null; // define full path to outFile (depends of asset_type) if (assetType == TYPE_DATABASE) { // check if database directory exists and create if necessary File dir = new File(context.getDatabasePath(fileName).getParent()); if (!dir.exists()) dir.mkdirs(); // create folders where write files outFile = context.getDatabasePath(fileName); } else { outFile = new File(context.getExternalFilesDir(assetType), fileName); } // copy file from asset if file doesn't exists or it need to be rewrited if (rewrite || (!outFile.exists())) { try { // get input stream from Assets in = new BufferedInputStream(assetManager.open(assetType + "/" + fileName), BUFFER_SIZE); out = new BufferedOutputStream(new FileOutputStream(outFile), BUFFER_SIZE); // copy from in to out copyFile(in, out); } catch (IOException ioe) { Log.e(TAG, "copyAssets(), Failed to copy asset: " + fileName, ioe); } finally { // try to close input stream try { in.close(); } catch (IOException ein) { Log.e(TAG, "copyAssets(), filed to close in, file: " + fileName, ein); } try { out.close(); } catch (IOException eout) { Log.e(TAG, "copyAssets(), filed to close out, file: " + fileName, eout); } } } } return true; }
public int dbFileOperation(String... params) { // 默认路径是 /data/data/(包名)/databases/*.db File dbFile = null; File backupDir = null; String command1 = params[1]; if (command1.equals(COMMAND_ISCONTACT)) { dbFile = mContext.getDatabasePath("/data/data/cn.sqy.contacts/databases/contact.db"); backupDir = new File(Environment.getExternalStorageDirectory(), "contactsBackup"); } else if (command1.equals(COMMAND_ISMESSAGE)) { dbFile = mContext.getDatabasePath("/data/data/cn.sqy.contacts/databases/msg.db"); backupDir = new File(Environment.getExternalStorageDirectory(), "msgBackup"); } else { return -1; } if (!backupDir.exists()) { backupDir.mkdirs(); } File backup = new File(backupDir, dbFile.getName()); String command2 = params[0]; if (command2.equals(COMMAND_BACKUP)) { try { if (command1.equals(COMMAND_ISCONTACT)) { backup.createNewFile(); fileCopy(dbFile, backup); return 0; } else { msgMgr.insertMsgsFromSysAllMsgs(); // 再将系统短信导入到数据库 backup.createNewFile(); // 最后再把数据库备份到SD卡上 fileCopy(dbFile, backup); return 3; } } catch (Exception e) { e.printStackTrace(); return -1; } } else if (command2.equals(COMMAND_RESTORE)) { try { if (command1.equals(COMMAND_ISCONTACT)) { fileCopy(backup, dbFile); return 1; } else { fileCopy(backup, dbFile); // 先把数据库从SD卡上恢复到我的数据库 msgMgr.insertIntoSysMsgFromMyMsg(); // 再从我的数据库导入到系统数据库中 return 4; } } catch (Exception e) { e.printStackTrace(); return -1; } } else { return -1; } }
public SQLiteRTree(Context context, String identifier) { super(context, context.getDatabasePath(DATABASE_NAME).getPath(), null, DATABASE_VERSION); Log.d("LST", context.getDatabasePath(DATABASE_NAME).getPath()); this.myContext = context; this.table_identifier = identifier; DBInit dbInit = new DBInit(context); if (!dbInit.dbExists()) { Log.d("LST", "DB did not exist, using dbInit to create now."); dbInit.init(); this.onCreate(this.getWritableDatabase()); } }
public static void extractContributorsCloudDatabase(Context context) { final int BUFFER = 1024; InputStream is = null; OutputStream os = null; File databasePath = context.getDatabasePath(DB_NAME); try { databasePath.getParentFile().mkdir(); is = context.getResources().getAssets().open(DB_NAME, AssetManager.ACCESS_BUFFER); os = new FileOutputStream(databasePath); int read = -1; byte[] data = new byte[BUFFER]; while ((read = is.read(data, 0, BUFFER)) != -1) { os.write(data, 0, read); } } catch (IOException ex) { Log.e(TAG, "Failed to extract contributors database"); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { // Ignore } } } }
private synchronized SQLiteDatabase getDatabase(Context context, boolean retryCopyIfOpenFails) { if (mDatabase == null) { File dbPath = context.getDatabasePath(DB_NAME); try { mDatabase = SQLiteDatabase.openDatabase( dbPath.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY); if (mDatabase == null) { Log.e(TAG, "Cannot open cloud database: " + DB_NAME + ". db == null"); return null; } return mDatabase; } catch (SQLException ex) { Log.e(TAG, "Cannot open cloud database: " + DB_NAME, ex); if (mDatabase != null && mDatabase.isOpen()) { try { mDatabase.close(); } catch (SQLException ex2) { // Ignore } } if (retryCopyIfOpenFails) { extractContributorsCloudDatabase(context); mDatabase = getDatabase(context, false); } } // We don't have a valid connection return null; } return mDatabase; }
public GlobalContactManager(Context context) { this.context = context; File file = context.getDatabasePath("none"); File databaseDir = file.getParentFile(); File[] listFiles = databaseDir.listFiles(); List<String> yjtUserIds = getYjtUserIds(context); for (int i = 0; i < listFiles.length; i++) { File dbFile = listFiles[i]; String name = dbFile.getName(); if (name.matches(CONTACT_DB_REGULAR)) { ContactManager contactManager = ContactManager.createContactManagerWithDBHelper( context, new ContactDBHelper(context, name)); String userId = name.substring(4); if (yjtUserIds.contains(userId)) { yjtUserContactManagers.add(contactManager); } else if (AccountManager.getCurrent(context).getId() != Long.parseLong(userId)) { contactManagers.add(contactManager); } else { // current user contactManager currentContactManager = ContactManager.getContactManager(context); } } } if (currentContactManager == null) { currentContactManager = ContactManager.getContactManager(context); } }
public void importContacts() throws Exception { String path = mContext.getDatabasePath(DATABASE_NAME).getPath(); Log.w(TAG, "Importing contacts from " + path); if (!new File(path).exists()) { Log.i(TAG, "Legacy contacts database does not exist"); return; } for (int i = 0; i < MAX_ATTEMPTS; i++) { try { mSourceDb = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY); importContactsFromLegacyDb(); Log.i(TAG, "Imported legacy contacts: " + mContactCount); mContactsProvider.notifyChange(); return; } catch (SQLiteException e) { Log.e(TAG, "Database import exception. Will retry in " + DELAY_BETWEEN_ATTEMPTS + "ms", e); // We could get a "database locked" exception here, in which // case we should retry Thread.sleep(DELAY_BETWEEN_ATTEMPTS); } finally { if (mSourceDb != null) { mSourceDb.close(); } } } }
public void copyAttachedDatabase(Context context, String databaseName) { final File dbPath = context.getDatabasePath(databaseName); // If the database already exists, return if (dbPath.exists()) { return; } // Make sure we have a path to the file dbPath.getParentFile().mkdirs(); // Try to copy database file try { final InputStream inputStream = context.getAssets().open(databaseName); final OutputStream output = new FileOutputStream(dbPath); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { output.write(buffer, 0, length); } output.flush(); output.close(); inputStream.close(); } catch (IOException e) { Log.e("Failed to open file", e); } }
private StaticDataStore(Context context, String caller) { super(context, DB_NAME, null, DB_VERSION); this.context = context; DB_PATH = context.getDatabasePath(DB_NAME).toString(); initialize(); Logging.Log(LOG_TAG, "DB opened by (initialized): " + caller); }
private SQLiteDatabase openDatabase(Database db) throws SQLiteException { Context context = AndroidServiceLocator.getContext(); return SQLiteDatabase.openDatabase( context.getDatabasePath(db.getName()).getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE); }
protected BasePropertiesDatabase(Context context, String dbName) { this.context = context.getApplicationContext(); if (!StringUtil.isEmpty(dbName)) { // 対象のDBが指定されている this.databaseFile = context.getDatabasePath(dbName); } }
static boolean isDbFileAvailable() { File dbFile = context.getDatabasePath(DATABASE_NAME); if (!dbFile.exists() || !dbFile.canWrite()) { return false; } return true; }
public void checkExistsDatabase(Context context) { File database = context.getDatabasePath("produtos.db"); if (!database.exists()) { Log.i("Database", "Not Found"); } else { Log.i("Database", "Found"); } }
public static void exportdb(Context context) { File database = context.getDatabasePath("dotasteam"); File exportDir = new File(Environment.getExternalStorageDirectory(), "dbBackup"); try { fileCopy(database, exportDir); } catch (IOException e) { e.printStackTrace(); } }
/** * Open input stream to read the binary key store database file. * * <p>Convenience function that mainly covers the various exceptions and handles them. * * @return {@code FileInputStream} or {@code null} in case of error. */ private static FileInputStream openInKeyStoreStream() { File dbFile = context.getDatabasePath(DATABASE_NAME); FileInputStream ksIn = null; try { ksIn = new FileInputStream(dbFile); } catch (FileNotFoundException e) { Log.e(TAG, "Cannot find key store database for KeyManager", e); } return ksIn; }
/** * Create and/or open a database that will be used for reading only. * * @return SQLiteDatabase对象 * @throws RuntimeException if cannot copy database from assets * @throws SQLiteException if the database cannot be opened */ public synchronized SQLiteDatabase getReadableDatabase() { File dbFile = context.getDatabasePath(databaseName); if (dbFile != null && !dbFile.exists()) { try { copyDatabase(dbFile); } catch (IOException e) { throw new RuntimeException("Error creating source database", e); } } return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY); }
@Override public void dataChanged() { // Copy Database to temp location try { FileUtils.copyFile( new FileInputStream(context.getDatabasePath("tac.db")), context.openFileOutput(BACKUP_LOCATION, Context.MODE_PRIVATE)); } catch (final Exception e) { Log.e(TAG, "Could not copy database to backup location", e); } super.dataChanged(); } // dataChanged
public void initInputMethod(KerKerInputCore core) { super.initInputMethod(core); _currentPage = 0; _currentCandidates = new ArrayList<CharSequence>(); final Context c = core.getFrontend(); _name = c.getString(R.string.changjei5); _dbpath = c.getDatabasePath("cj5.db").toString(); keyNames = new HashMap<CharSequence, CharSequence>(); try { db = SQLiteDatabase.openDatabase(_dbpath, null, SQLiteDatabase.OPEN_READONLY); loadKeyNames(); db.close(); } catch (SQLiteException ex) { db = null; System.out.println("Error, no database file found. Copying..."); new Thread( new Runnable() { public void run() { copying = true; // Create the database (and the directories required) then close it. db = c.openOrCreateDatabase("cj5.db", 0, null); db.close(); try { OutputStream dos = new FileOutputStream(_dbpath); InputStream dis = new FileInputStream("/sdcard/cj5.db"); byte[] buffer = new byte[32768]; while (dis.read(buffer) > 0) { dos.write(buffer); } dos.flush(); dos.close(); dis.close(); } catch (IOException e) { e.printStackTrace(); } db = SQLiteDatabase.openDatabase(_dbpath, null, SQLiteDatabase.OPEN_READONLY); db.setLocale(Locale.TRADITIONAL_CHINESE); loadKeyNames(); copying = false; } }) .start(); } }
/** Restore the database from a file. */ @SuppressWarnings("ConstantConditions") public void restoreDatabase(File file) { close(); File oldDb = new File(String.valueOf(mContext.getDatabasePath(getDatabaseName()))); if (file.exists()) { try { copyFile(new FileInputStream(file), new FileOutputStream(oldDb)); } catch (IOException e) { e.printStackTrace(); } getWritableDatabase().close(); } }
/** * Constructor. * * @param ctx Context * @param name name * @param factory factory * @param version version */ public TracscanSQLiteOpenHelperBase( final Context ctx, final String name, final CursorFactory factory, final int version) { super(ctx, name, factory, version); this.ctx = ctx; DB_NAME = name; DB_PATH = ctx.getDatabasePath(DB_NAME).getAbsolutePath(); try { this.ctx.getAssets().open(DB_NAME); assetsExist = true; } catch (IOException e) { assetsExist = false; } }
/** * Create and/or open a database. This will be the same object returned by {@link * #getWritableDatabase} unless some problem, such as a full disk, requires the database to be * opened read-only. In that case, a read-only database object will be returned. If the problem is * fixed, a future call to {@link #getWritableDatabase} may succeed, in which case the read-only * database object will be closed and the read/write object will be returned in the future. * * <p class="caution">Like {@link #getWritableDatabase}, this method may take a long time to * return, so you should not call it from the application main thread, including from {@link * android.content.ContentProvider#onCreate ContentProvider.onCreate()}. * * @throws SQLiteException if the database cannot be opened * @return a database object valid until {@link #getWritableDatabase} or {@link #close} is called. */ public synchronized SQLiteDatabase getReadableDatabase() { if (mDatabase != null) { if (!mDatabase.isOpen()) { // darn! the user closed the database by calling mDatabase.close() mDatabase = null; } else { return mDatabase; // The database is already open for business } } if (mIsInitializing) { throw new IllegalStateException("getReadableDatabase called recursively"); } try { return getWritableDatabase(); } catch (SQLiteException e) { if (mName == null) throw e; // Can't open a temp database read-only! Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e); } SQLiteDatabase db = null; try { mIsInitializing = true; String path = mContext.getDatabasePath(mName).getPath(); db = SQLiteDatabase.openDatabase( path, mPasswd, mFactory, SQLiteDatabase.OPEN_READONLY, mErrorHandler); if (db.getVersion() != mNewVersion) { throw new SQLiteException( "Can't upgrade read-only database from version " + db.getVersion() + " to " + mNewVersion + ": " + path); } onOpen(db); Log.w(TAG, "Opened " + mName + " in read-only mode"); mDatabase = db; return mDatabase; } finally { mIsInitializing = false; if (db != null && db != mDatabase) db.close(); } }
public SQLiteDatabase openDataBase() throws SQLException { File dbFile = ctx.getDatabasePath(DATABASE_NAME); if (!dbFile.exists()) { try { CopyDataBaseFromAsset(); System.out.println("Copying sucess from Assets folder"); } catch (IOException e) { throw new RuntimeException("Error creating source database", e); } } return SQLiteDatabase.openDatabase( dbFile.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY); }
/** If database exists, no tasks but metadata, and a backup file exists, restore it */ private void databaseRestoreIfEmpty(Context context) { try { if (AstridPreferences.getCurrentVersion() >= UpgradeService.V3_0_0 && !context.getDatabasePath(database.getName()).exists()) { // we didn't have a database! restore latest file File directory = BackupConstants.defaultExportDirectory(); if (!directory.exists()) { return; } File[] children = directory.listFiles(); AndroidUtilities.sortFilesByDateDesc(children); if (children.length > 0) { TasksXmlImporter.importTasks(context, children[0].getAbsolutePath(), null); } } } catch (Exception e) { Log.w("astrid-database-restore", e); // $NON-NLS-1$ } }
/** * Check if the database exist * * @return true if it exists, false if it doesn't */ public static boolean checkDataBaseExists(Context context) { if (StoreConfig.debug) { Log.d(TAG, "Checking if database exists"); } SQLiteDatabase checkDB = null; try { checkDB = SQLiteDatabase.openDatabase( context.getDatabasePath(DATABASE_NAME).getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY); checkDB.close(); } catch (SQLiteException e) { if (StoreConfig.debug) { Log.d(TAG, "Database doesn't exist"); } } return checkDB != null; }
/** Creates a empty database on the system and rewrites it with your own database. */ public void createDataBase() throws IOException { File dbFile = myContext.getDatabasePath(DB_NAME); boolean dbExist = dbFile.exists(); // By calling this method and empty database will be created into // the default system path // of your application so we are gonna be able to overwrite that // database with our database. this.getReadableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } }
public boolean importContacts() throws Exception { String path = mContext.getDatabasePath(DATABASE_NAME).getPath(); File file = new File(path); if (!file.exists()) { Log.i(TAG, "Legacy contacts database does not exist at " + path); return true; } Log.w(TAG, "Importing contacts from " + path); for (int i = 0; i < MAX_ATTEMPTS; i++) { try { mSourceDb = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY); importContactsFromLegacyDb(); Log.i(TAG, "Imported legacy contacts: " + mContactCount); mContactsProvider.notifyChange(); return true; } catch (SQLiteException e) { Log.e(TAG, "Database import exception. Will retry in " + DELAY_BETWEEN_ATTEMPTS + "ms", e); // We could get a "database locked" exception here, in which // case we should retry Thread.sleep(DELAY_BETWEEN_ATTEMPTS); } finally { if (mSourceDb != null) { mSourceDb.close(); } } } long oldDatabaseSize = file.length(); mEstimatedStorageRequirement = oldDatabaseSize * DATABASE_SIZE_MULTIPLIER / 1024 / 1024; if (mEstimatedStorageRequirement < DATABASE_MIN_SIZE) { mEstimatedStorageRequirement = DATABASE_MIN_SIZE; } return false; }
public static boolean checkDataBase(Context context) { SQLiteDatabase checkDB = null; try { File database = context.getDatabasePath(DATABASE_NAME); if (database.exists()) { Log.i("Database", "Found"); String myPath = database.getAbsolutePath(); Log.i(LOG, myPath); checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); // return true; } else { // Database does not exist so copy it from assets here Log.i(LOG, "Not Found"); // return false; } } catch (SQLiteException e) { Log.i(LOG, "Not Found"); } finally { if (checkDB != null) { checkDB.close(); } } return checkDB != null ? true : false; }
public static boolean destroy(Context context) { return context.getDatabasePath(DATABASE_NAME_OLD).delete(); }