我能够在我的项目中拼凑出以下解决方案:
// Grab all data from the DB in question (TaskDB):
RealmResults<TaskDB> resultsDB = realm.where(TaskDB.class).findAll();
// Here we need to put in header fields
String dataP = null;
String header = DataExport.grabHeader(realm, "TaskDB");
// We write the header to file
savBak(header);
// Now we write all the data corresponding to the fields grabbed above:
for (TaskDB taskitems: resultsDB) {
dataP = taskitems.toString();
// We process the data obtained and add commas and formatting:
dataP = dataProcess(dataP);
// Workaround to remove the last comma from final string
int total = dataP.length() - 1;
dataP = dataP.substring(0,total);
// We write the data to file
savBak(dataP);
}
我将尽我所能解释它在做什么,并包括所有相应的代码(全部参考第一个代码块)。
我首先使用我在单独的类 (DataExport.grabHeader) 中编写的以下方法来抓取标题。它有 2 个参数:有问题的领域对象和 DB 对象模型名称:
public static String grabHeader(Realm realm, String model){
final RealmSchema schema = realm.getSchema();
final RealmObjectSchema testSchema = schema.get(model);
final String header = testSchema.getFieldNames().toString();
String dataProcessed = new String();
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(header);
while(m.find()) {
dataProcessed += m.group(1).trim().replaceAll("\\p{Z}","");
}
return dataProcessed;
在grabHeader 中,我应用了一些正则表达式魔法并吐出一个字符串,该字符串将用作带有适当逗号的标题(String dataProcessed)。
在这种情况下,在获得所需数据后,我使用另一种方法(savBak)将信息写入一个采用 1 个字符串参数的文件:
@Override
public void savBak(String data){
FileOutputStream fos = null;
try {
fos = openFileOutput(FILE_NAME, MODE_PRIVATE | MODE_APPEND);
fos.write(data.getBytes());
fos.write("\n".getBytes());
Log.d("tester", "saved to: " + getFilesDir() + "/" + FILE_NAME);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
“savBak”方法将信息写入到变量中指定的 FILE_NAME 中,我们得到了头信息。写完标题后,我们使用 forloop 对 DB 执行基本相同的过程,但我还必须包含 2 行以在处理该行后删除尾随逗号。每一行都附加到文件和中提琴,CSV 格式很好。
从这里,您可以使用其他现有方法将 CSV 转换为 JSON 和其他任何方法,以及通过 JSON 将信息放回领域。当涉及到主键等更高级的元素时,我不确定,但它可以满足我的特定项目需求。
请原谅任何“糟糕的代码”做法,因为我是 Java/Android 的新手,通常来自“几乎是中级”的 Python 背景,所以希望这是有道理的。