android导入外部数据库
public class DatabaseUtils {
public static String data_path="" ;
public File dataFile=null;
public Context context;
public static final String DB_NAME="english.db";
public DatabaseUtils(Context context) {
this.context=context;
data_path="/data"+ Environment.getDataDirectory().getAbsolutePath() + "/"+context.getPackageName()+"/databases/";
dataFile=new File(data_path);
}
public void outPutDatabase() throws IOException {
if (!dataFile.exists()) {//包下面的databases有可能不存在
dataFile.mkdirs();
}
File dbFile=new File(dataFile, DB_NAME);
if (!dbFile.exists()) {
Log.i("MainActivity", "数据库文件不存在,准备导入 ");
//获取数据库文件的输入流
InputStream inputStream=context.getAssets().open("english.db");
FileOutputStream fileOutputStream=new FileOutputStream(dbFile);
byte[] buffer=new byte[400000];
int count=0;
while ((count=inputStream.read())>0) {
fileOutputStream.write(buffer,0,count);
Log.i("MainActivity", "正在输出");
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
Toast.makeText(context, "导入数据库文件成功", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context, "数据库已经存在", Toast.LENGTH_LONG).show();
Log.i("MainActivity", "数据库已经存在");
}
}
}
之前报了有这么一个错误
09-10 00:34:25.254: W/System.err(9596): java.io.FileNotFoundException: /data/data/com.kangda.app/databases/english.db: open failed: EISDIR (Is a directory)
其实原因就是databases这个目录是不存在的,然而,我却直接使用/data/data/com.kangda.app/databases/english.db去打开输出流,应该先创建好不存在的databases。
上面那个代码有点问题现在更正,上面inputStream.read()没有传入buffer:
public class DatabaseUtils {
public static String data_path="" ;
public File dataFile=null;
public Context context;
public static final String DB_NAME="english.db";
public DatabaseUtils(Context context) {
this.context=context;
data_path="/data"+ Environment.getDataDirectory().getAbsolutePath() + "/"+context.getPackageName()+"/databases/";
dataFile=new File(data_path);
}
public SQLiteDatabase outPutDatabase() throws IOException {
SQLiteDatabase db=null;
if (!dataFile.exists()) {//包下面的databases有可能不存在
dataFile.mkdirs();
}
File dbFile=new File(dataFile, DB_NAME);
if (!dbFile.exists()) {
Log.i("MainActivity", "数据库文件不存在,准备导入 ");
//获取数据库文件的输入流
InputStream inputStream=context.getResources().openRawResource(R.raw.english);
FileOutputStream fileOutputStream=new FileOutputStream(dbFile);
byte[] buffer=new byte[1024];
int count=-1;
while ((count=inputStream.read(buffer))!=-1) {
fileOutputStream.write(buffer,0,count);
Log.i("MainActivity", "正在输出");
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
Toast.makeText(context, "导入数据库文件成功", Toast.LENGTH_LONG).show();
// db = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, Context.MODE_PRIVATE);
}else {
Toast.makeText(context, "数据库已经存在", Toast.LENGTH_LONG).show();
Log.i("MainActivity", "数据库已经存在");
}
return db;
}
}
关注我