Android复制Assets目录下的文件到/data/data目录
目的
l? 在項目開發時,尤其是游戲開發,有時候需要把特定的文件放在data/data目錄下,比如sqlite數據庫中,我們會事先創建數據庫并在里面加入需要的數據,比如游戲的關卡數據。而android提供的sqlite框架似乎只能讀取data/data目錄下的數據庫文件,此時就很有必要先放在Assets目錄下,之后再復制到data/data目錄下。廢話不多說,直接上代碼!
實現代碼
| void copyData() ?? { ???? InputStream in = null; ???? FileOutputStream out = null; ???? String path = this.getApplicationContext().getFilesDir() ???? .getAbsolutePath() + "/mydb.db3"; // data/data目錄 ???? File file = new File(path); ???? if (!file.exists()) { ??????? try ??????? { ????????? in = this.getAssets().open("db/mydb.db3"); // 從assets目錄下復制 ????????? out = new FileOutputStream(file); ????????? int length = -1; ????????? byte[] buf = new byte[1024]; ????????? while ((length = in.read(buf)) != -1) ????????? { ???????????? out.write(buf, 0, length); ????????? } ????????? out.flush(); ??????? } ??????? catch (Exception e) ??????? { ????????? e.printStackTrace(); ??????? } ??????? finally{ ????????? if (in != null) ????????? { ???????????? try { ? ?????????????? in.close(); ? ???????????? } catch (IOException e1) { ? ?????????????? // TODO Auto-generated catch block ? ?????????????? e1.printStackTrace(); ???????????? } ????????? } ????????? if (out != null) ????????? { ???????????? try { ?????????????? out.close(); ???????????? } catch (IOException e1) { ?????????????? // TODO Auto-generated catch block ?????????????? e1.printStackTrace(); ???????????? } ????????? } ??????? } ???? } ?? } ?? } |
?
總結
以上是生活随笔為你收集整理的Android复制Assets目录下的文件到/data/data目录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决AndroidManifest.xm
- 下一篇: 关掉Ctrl+Alt+方向键转屏功能