【发布时间】:2009-12-23 16:28:43
【问题描述】:
我的应用程序的数据库需要填充大量数据,
所以在onCreate()期间,不仅仅是一些创建表sql
说明,有很多插页。我选择的解决方案是
将所有这些指令存储在 res/raw 中的 sql 文件中,并且
加载了Resources.openRawResource(id)。
它运作良好,但我面临编码问题,我有一些强调 在我的应用程序中出现错误的 sql 文件中的字符。这 我这样做的代码:
public String getFileContent(Resources resources, int rawId) throws
IOException
{
InputStream is = resources.openRawResource(rawId);
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
return new String(buffer);
}
public void onCreate(SQLiteDatabase db) {
try {
// get file content
String sqlCode = getFileContent(mCtx.getResources(), R.raw.db_create);
// execute code
for (String sqlStatements : sqlCode.split(";"))
{
db.execSQL(sqlStatements);
}
Log.v("Creating database done.");
} catch (IOException e) {
// Should never happen!
Log.e("Error reading sql file " + e.getMessage(), e);
throw new RuntimeException(e);
} catch (SQLException e) {
Log.e("Error executing sql code " + e.getMessage(), e);
throw new RuntimeException(e);
}
我发现避免这种情况的解决方案是加载 sql 指令
从一个巨大的static final String 而不是一个文件,以及所有
重音字符看起来很好。
但是没有比大的加载 sql 指令更优雅的方式吗?
static final String 属性与所有 sql 指令?
【问题讨论】: