//数据库保存位置: res/raw/数据库
//代码添加到程序开始页面
//例子如下
public class FoodHealthActivity extends Activity {
public static String dbName = "foodHealth.db";// 数据库的名字
private static String DATABASE_PATH = "/data/data/hlju.edu.FoodHealth/databases/";// 数据库在手机里的路径
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 判断数据库是否存在
boolean dbExist = checkDataBase();
if (dbExist) {
} else {// 不存在就把raw里的数据库写入手机
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* 判断数据库是否存在
*
* @return false or true
*/
public boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String databaseFilename = DATABASE_PATH + dbName;
checkDB = SQLiteDatabase.openDatabase(databaseFilename, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* 复制数据库到手机指定文件夹下
*
* @throws IOException
*/
public void copyDataBase() throws IOException {
String databaseFilenames = DATABASE_PATH + dbName;
File dir = new File(DATABASE_PATH);
if (!dir.exists())// 判断文件夹是否存在,不存在就新建一个
dir.mkdir();
FileOutputStream os = null;
try {
os = new FileOutputStream(databaseFilenames);// 得到数据库文件的写入流
} catch (FileNotFoundException e) {
e.printStackTrace();
}
InputStream is = FoodHealthActivity.this.getResources()
.openRawResource(R.raw.foodhealth);// 得到数据库文件的数据流
byte[] buffer = new byte[8192];
int count = 0;
try {
while ((count = is.read(buffer)) > 0) {
os.write(buffer, 0, count);
os.flush();
}
} catch (IOException e) {
}
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}