2013-07-10 48 views
0

這裏複製數據庫是我使用的代碼(在許多答案中):Android的 - 從資產

InputStream myInput; 
     try { 
      myInput = iNezamApplication.getAppContext().getAssets().open(DB_NAME); 
      String outFileName = DB_PATH + DB_NAME; 

      OutputStream myOutput = new FileOutputStream(outFileName); 
      byte[] buffer = new byte[1024]; 
      int length; 
      while ((length = myInput.read(buffer))>0){ 
       myOutput.write(buffer, 0, length); 
      } 

      myOutput.flush(); 
      myOutput.close(); 
      myInput.close(); 

     } catch (IOException e1) { 
      e1.printStackTrace(); 

     } 

但是,我總是到達OutpoutStream線後得到一個異常:

java.io.FileNotFoundException: /data/data/package_name/databases/databasename.db: open failed: ENOENT (No such file or directory) 
+3

請考慮切換到測試,調試,並支持'SQLiteAssetHelper',而不是年齡,不支持的鱈魚「在許多答案中找到」:https://github.com/jgilfelt/android-sqlite-asset-helper – CommonsWare

+0

謝謝,我知道它,但我不想使用它。我只需要回答我的問題。 –

回答

6

我想是這樣的一個文件對象..

final String[] sample_dbName = {"DrugsNew.db"}; 

    int assetDbSize = sample_dbName.length; 
    File databaseFile = new File("/data/data/com.handyrep2.ui/databases"); 

    // check if databases folder exists, if not create one and its subfolders 
    if (!databaseFile.exists()){ 
     databaseFile.mkdir(); 
    } 

     for(int i=0;i<assetDbSize;i++){ 
      String outFilename =null; 

     outFilename = "/data/data/com.handyrep2.ui/databases"+ "/" + sample_dbName[i]; 

      File sampleFile = new File(outFilename); 

       try { 
        InputStream in = activity.getAssets().open("offlinedb/"+sample_dbName[i]); 

        OutputStream out = new FileOutputStream(outFilename); 
        // Transfer bytes from the sample input file to the sample output file 
        byte[] buf = new byte[1024]; 
        int len; 
        while ((len = in.read(buf)) > 0) { 
         out.write(buf, 0, len); 
        } 
        out.flush(); 
        // Close the streams 
        out.close(); 
        in.close(); 
       }catch(IOException e) { 

       } 


     } 
+0

需要首先創建數據庫目錄感謝:) –

1

「package_name」是否代替真正的軟件包名稱,只是爲了將其發佈到此處或在DB_PATH中真正使用它? :)

+0

不,這是真正的包名,我只是在這裏省略:) –

+0

好的。我不知道。我們在當前項目中使用的方法幾乎相同 - 工作良好,所以目前看不到任何錯誤。對不起: – a11n

1

必須創建第一

+0

也沒有工作 –