private SQLiteDatabase openDatabase() android
{ spa
try 對象
{ get
// 得到dictionary.db文件的絕對路徑 it
String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME; io
File dir = new File(DATABASE_PATH); class
// 若是/sdcard/dictionary目錄中存在,建立這個目錄 List
if (!dir.exists()) 程序
dir.mkdir(); 方法
// 若是在/sdcard/dictionary目錄中不存在
// dictionary.db文件,則從res/raw目錄中複製這個文件到
// SD卡的目錄(/sdcard/dictionary)
if (!(new File(databaseFilename)).exists())
{
// 得到封裝dictionary.db文件的InputStream對象
InputStream is = getResources().openRawResource(R.raw.dictionary);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte[] buffer = new byte[8192];
int count = 0;
// 開始複製dictionary.db文件
while ((count = is.read(buffer)) > 0)
{
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
// 打開/sdcard/dictionary目錄中的dictionary.db文件
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
databaseFilename, null);
return database;
}
catch (Exception e)
{
}
return null;
}
在openDatabase方法中使用了幾個常量,這些常量是在程序的主類(Main)中定義的,代碼以下:
代碼
public class Main extends Activity implements OnClickListener, TextWatcher
{
private final String DATABASE_PATH = android.os.Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/dictionary";
private final String DATABASE_FILENAME = "dictionary.db";
}