我试图将我的数据库文件复制到sdcard中。我正在使用这些代码来执行此操作:
private static String DB_PATH = Environment.getExternalStorageDirectory().toString()+"/";
private static final String DATABASE_NAME = "story.sql";
private void copyDataBase() throws IOException {
InputStream myInput = helperContext.getAssets().open(DATABASE_NAME);
String outFileName = DB_PATH + DATABASE_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();
}
当我调试代码异常时抛出
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
07-26 14:58:10.689: ERROR/AndroidRuntime(7723): Uncaught handler: thread main exiting due to uncaught exception
07-26 14:58:10.709: ERROR/AndroidRuntime(7723): java.lang.Error: Error copying database
07-26 14:58:10.709: ERROR/AndroidRuntime(7723): at org.android.story.SqliteManager$DatabaseHelper.createDataBase(SqliteManager.java:272)
07-26 14:58:10.709: ERROR/AndroidRuntime(7723): at org.android.story.SqliteManager.open(SqliteManager.java:62)
07-26 14:58:10.709: ERROR/AndroidRuntime(7723): at org.android.story.MainMenu.onCreate(MainMenu.java:21)
我试过在Android OS 2.1上的结果是一样的。在我试用Android 2.3.3操作系统版本后,它的魅力很有用。还尝试了我的Android手机,它有1.6 OS版本和较小的数据库(我的数据库是9.8 MB,并改为320 KB大小)它工作正常。那么为什么这个代码适用于2.3.3或更小的数据库但不适用于1.6或2.1?是否有任何解决方法在1.6中使用它?
编辑:我写这个函数调用copyDataBase()
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}