把须要的数据库放在工程的assets目录下,这里以“address.db”为例 java
/** * 拷贝须要用到的数据库文件 */ new Thread() { public void run() { Message msg = Message.obtain(); try { InputStream is = getAssets().open("address.db"); // 释放文件到当前应用程序的目录 // data/data/com.example.lx/files/address.db File destFile = new File(getFilesDir(),"address.db"); File file = FileCopyUtil.copy(is, destFile.getAbsolutePath()); if (file == null) { // 拷贝失败 msg.what = COPY_ERROR; } else { // 拷贝成功 msg.what = COPY_SUCCESS; } } catch (IOException e) { e.printStackTrace(); // 拷贝失败 msg.what = COPY_ERROR; }finally{ handler.sendMessage(msg); } }; }.start();
里面调用的copyutil实际就是一个IO流拷贝类: 数据库
public class FileCopyUtil { /** * * @param is 源文件输入流 * @param path 拷贝到的地址 * @return null表明拷贝失败,成功就返回拷贝后的文件 */ public static File copy(InputStream is, String path){ try { File file = new File(path); FileOutputStream fos = new FileOutputStream(file); byte [] buffer = new byte[1024]; int len; while((len = is.read(buffer)) != -1){ fos.write(buffer, 0, len); } fos.flush(); fos.close(); is.close(); return file; } catch (Exception e) { e.printStackTrace(); return null; } } }
这样就把数据库拷贝到了data/data/程序包名/files目录下 code
注意:这个方法在Android2.3之前,所要拷贝的源文件的大小不能超过1M,2.3之后没有了这个限制,因此要明确你模拟器的版本 get