怎么在程序初次运行时将预制的数据库拷贝到指定位置
怎样在程序初次运行时将预制的数据库拷贝到指定位置
新人求教
上面的代码执行后没有创建databases文件夹,即使我在虚拟机里自建了databases文件夹也不能拷贝
------解决思路----------------------
判断是不是错了?
源码里说了:
Returns the number of bytes actually read or -1 if the end of the stream has been reached.
应该是判断-1吧,不然会无限循环的
新人求教
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.os.Bundle;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
public class InitActivity extends Activity {
String Path = "mnt/data/data/com.wrdggess.init/databases";
String dbName = "gess.db";
Context context = this.getBaseContext();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_init);
copyDb(Path);
}
public void copyDb(String path) {
File file = new File(Path, dbName); //获取参数
if (!file.exists()) {
file.getParentFile().mkdirs(); //判断文件是否存在
}
InputStream iStream = this.getBaseContext().getResources()
.openRawResource(R.raw.gess); //提取数据库文件
try {
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int count = 0; // 将静态数据库文件拷贝到目的地
while ((count = iStream.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
fos.close();
Toast.makeText(context, "本地数据库加载成功", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) { // TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) { // TODO Auto-generated catch block
Toast.makeText(context, "本地数据库加载失败", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
上面的代码执行后没有创建databases文件夹,即使我在虚拟机里自建了databases文件夹也不能拷贝
------解决思路----------------------
while ((count = iStream.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
判断是不是错了?
源码里说了:
Returns the number of bytes actually read or -1 if the end of the stream has been reached.
应该是判断-1吧,不然会无限循环的