1、SQLITE数据库作为单一文件可以放到SDCARD或手机ROM内存供程序访问,嵌入式。
2、在ANDROID程序模拟器调试时的FILE
EXPLORER视察中可以查看到手机内存的文件存在目录,SQLITE数据库文件通常放到data/data/包名目录/下,放data/data/包名目录/lib目录测试打不开文件流。
3、数据库操作类
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
import com.calendar.demo.R;
public class DbManager {
private final int BUFFER_SIZE = 400000;
public static final String DB_NAME = "chcanlendar.db"; //
保存的数据库文件名
public static final String PACKAGE_NAME = "com.calendar.demo";
public static final String DB_PATH = "/data"
+ Environment.getDataDirectory().getAbsolutePath() + "/"
+ PACKAGE_NAME; // 在手机里存放数据库的位置
public SQLiteDatabase database;
public Context context;
public void openDatabase() {
this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
}
public DbManager(Context context) {
super();
this.context = context;
}
private SQLiteDatabase openDatabase(String dbfile) {
try {
if (!(new File(dbfile).exists())) {//
判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库
InputStream is = this.context.getResources().openRawResource(
R.raw.chcanlendar); // 欲导入的数据库
FileOutputStream fos = new FileOutputStream(dbfile);
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
null);
return db;
} catch (FileNotFoundException e) {
Log.e("Database", "File not found");
e.printStackTrace();
} catch (IOException e) {
Log.e("Database", "IO exception");
e.printStackTrace();
}
return null;
}
public void closeDatabase() {
this.database.close();
}
}