public SQLiteDatabase initdatabase() {
// TODO Auto-generated method stub
if (!new File(databasepath).exists()) {
new File(databasepath).mkdir();
}
File databasefile = new File(databasepath + databasename);
if (!databasefile.exists()) {
try {
System.out.println(databasepath);
databasefile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = activity.getResources().getAssets()
.open(databasename);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
outputStream = new FileOutputStream(databasepath + databasename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
int length;
try {
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
buffer = new byte[1024];// 一次写入128B的数据
System.out.println("write over!");
}
} catch (IOException e) {
e.printStackTrace();
}
// Close the streams
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
sqLiteDatabase = null;
sqLiteDatabase = SQLiteDatabase.openDatabase(databasepath
+ databasename, null, SQLiteDatabase.OPEN_READWRITE);
Toast.makeText(activity, "位于本地的数据库初始化完成!", Toast.LENGTH_LONG)
.show();
}
sqLiteDatabase = SQLiteDatabase.openDatabase(databasepath
+ databasename, null, SQLiteDatabase.OPEN_READWRITE);
return sqLiteDatabase;
}
为什么一个初始化的代码要那么长? 哪些是可以省略的?
数据库
------解决方案--------------------
public SQLiteDatabase initdatabase() throws Exception {
if (!new File(databasepath).exists()) {
new File(databasepath).mkdir();
}
File databasefile = new File(databasepath + databasename);
if (!databasefile.exists()) {
System.out.println(databasepath);
databasefile.createNewFile();