我编写代码将房间数据库数据导出到 CSV 文件,并使用存储访问框架从中导入数据。它可以工作,但我的房间数据库有两个实体类,因此还有一个列表。
所以我想在同一个CSV文件里多写入和读取一个列表,这样用户就可以一键备份和恢复数据了
有办法吗?
谢谢。
出口:
public void exportCSV() {
Intent intent2 = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent2.setType("text/csv");
intent2.putExtra(Intent.EXTRA_TITLE, "db_backUp");
startForExportResult.launch(intent2);
}
进口:
public void importCSV() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("text/*");
intent.putExtra(Intent.EXTRA_TITLE, "db_backUp");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startForImportResult.launch(intent);
}
ActivityResultLaunche:export
ActivityResultLauncher<Intent> startForExportResult = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(), result -> {
Intent intent = result.getData();
if(intent != null){
Uri title = intent.getData();
recordList.clear();
db = Room.databaseBuilder(getContext().getApplicationContext(), DeckRoomDatabase.class, "deck_database")
.allowMainThreadQueries().build();
deckDao = db.deckDao();
List<Deck> decks = deckDao.getAllDecksForCSV();
recordList = (ArrayList<Deck>) decks;
if(title != null && result.getResultCode() == RESULT_OK){
try(BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
getContext().getContentResolver().openOutputStream(title)))){
for(int i = 0; i < recordList.size(); i++){
writer.append("" + recordList.get(i).getName());
writer.append(",");
writer.append("" + recordList.get(i).getListCount());
writer.append(",");
writer.append("" + recordList.get(i).getDateTime());
writer.append(",");
writer.append("" + recordList.get(i).getParameter());
writer.append("\n");
}
writer.flush();
writer.close();
Toast.makeText(this.getContext(), "Backup Export to:" + title.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e){
e.printStackTrace();
Toast.makeText(this.getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
ActivityResultLaunche:import
ActivityResultLauncher<Intent> startForImportResult = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(), result -> {
Intent intent = result.getData();
if(intent != null){
Uri uri = intent.getData();
if(uri != null && result.getResultCode() == RESULT_OK){
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(
getContext().getContentResolver().openInputStream(uri)))){
String line;
while ((line = reader.readLine()) != null){
String[] nextLine = line.split(",", 4);
if(nextLine.length != 4) {
continue;
}
String name = nextLine[0];
String listCount = nextLine[1];
String dateTime = nextLine[2];
String parameter = nextLine[3];
deckDao.insertDeck(new Deck(name, Integer.parseInt(listCount), LocalDateTime.parse(dateTime),
Integer.parseInt(parameter)));
}
Toast.makeText(this.getContext(), "Backup Restored...", Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(this.getContext(), "" + e, Toast.LENGTH_SHORT).show();
}
}
}
});