2017-10-15 58 views
-1

我從內部存儲器複製數據庫到外部,但似乎有什麼錯誤。因爲裏面沒有桌子。 我覺得只是一個空文件被創建。 同時,我用ActiveAndroid創建源數據庫文件,並使用Filechanel複製文件我將數據庫複製到外部存儲器。但它沒有源表

public class DbExportImport { 

/** Directory that files are to be read from and written to **/ 
protected static final File DATABASE_DIRECTORY = 
     new File(Environment.getExternalStorageDirectory(),"mydirectory"); 

public static final String PACKAGE_NAME = "example.com.testp"; 

public static final String DATABASE_NAME = "database1.db"; 

/** Contains: /data/data/com.example.app/databases/example.db **/ 
private static final File DATA_DIRECTORY_DATABASE = 
     new File(Environment.getDataDirectory() + 
       "/data/" + PACKAGE_NAME + 
       "/databases/" + DATABASE_NAME); 

public static boolean exportDb(){ 

    // if external torage is present 
    if(! SdIsPresent()) return false; 

    File dbFile = DATA_DIRECTORY_DATABASE; 

    String filename = "backupdb.db"; 

    File exportDir = DATABASE_DIRECTORY; 

    File file = new File(exportDir, filename); 

    if (!exportDir.exists()) { 
     exportDir.mkdirs(); 
    } 

    try { 
     file.createNewFile(); 
     copyFile(dbFile, file); 
     return true; 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return false; 
    } 
} 


private static void copyFile(File src, File dst) throws IOException { 

    FileChannel inChannel = new FileInputStream(src).getChannel(); 

    FileChannel outChannel = new FileOutputStream(dst).getChannel(); 

    try { 
        inChannel.transferTo(0, inChannel.size(), outChannel); 
    } finally { 
     if (inChannel != null) 
      inChannel.close(); 
     if (outChannel != null) 
      outChannel.close(); 
    } 
} 
+0

是什麼讓你認爲它沒有表?上述代碼都沒有嘗試將數據庫看作是一個sqlite數據庫,它只是將其視爲普通文件。 – MikeT

+0

你好。我看到複製數據庫與sqlite3命令行程序。但沒有表中。 – hassan

+0

當數據庫不存在時,您可能會用sqlite命令/方法打開數據庫,因此數據庫已經創建而沒有表。例如'SQLiteDatabase db = openOrCreateDatabase(「mydb」,MODE_PRIVATE,null);'會做到這一點。 – MikeT

回答

0

不知道有關的所有設備同樣的事情(我用的LG智能手機進行測試) 問題是的擴展文件(.db的)。我們不應該寫它來訪問私有存儲/數據/數據庫... 我使用context.getDatabasePath()以安全的方式獲取數據庫路徑。 在exportDb功能我用copyFile(context.getDatabasePath("database1"),file)代替copyFile(dbFile, file); 或者你可以改變public static final String DATABASE_NAME = "database1.db";public static final String DATABASE_NAME = "database1"; 但第一種方法似乎是更安全的

相關問題