如何以csv格式将数据库文件从模拟器存储到SD卡?
我创建了这个课程,但我不知道我应该在哪里打电话。
public class MyDatabaseTools {
private String appName = "LogCard";
private String packageName = "com.android.logcard";
SQLiteOpenHelper sqlitehelper;
public boolean backup() {
boolean rc = false;
boolean writeable = isSDCardWriteable();
if (writeable) {
File file = new File(Environment.getDataDirectory() + "/data/" + packageName + "/databases/" + sqlitehelper.getDatabaseName());
File fileBackupDir = new File(Environment.getExternalStorageDirectory(), appName + "/backup");
if (!fileBackupDir.exists()) {
fileBackupDir.mkdirs();
}
if (file.exists()) {
File fileBackup = new File(fileBackupDir, sqlitehelper.getDatabaseName());
try {
fileBackup.createNewFile();
FileUtils.copyFile(file, fileBackup);
rc = true;
} catch (IOException ioException) {
//
} catch (Exception exception) {
//
}
}
}
return rc;
}
private boolean isSDCardWriteable() {
boolean rc = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
rc = true;
}
return rc;
}
public MyDatabaseTools(final Context context, final String appName) {
this.appName = appName;
packageName = context.getPackageName();
}
如果这个课程有所帮助,应该在哪里开课?我从here
获取了此代码答案 0 :(得分:0)
我纠正了这个错误。打开数据库后添加了以下代码,csv文件保存在存储卡中。
File dbFile =new File(Environment.getDataDirectory() +"/data/com.example.logcard/databases/login.db");
// DbClass DBob = new DbClass(MyDatabaseActivity.this);
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "basic_details.csv");
try
{
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
// dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
// login=login.open1();
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor curCSV=db.rawQuery("SELECT * FROM LOGCARD",null);
// Cursor curCSV = db.rawQuery("SELECT * FROM table_ans12",null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2),curCSV.getString(3),curCSV.getString(4),
curCSV.getString(5),curCSV.getString(6),curCSV.getString(7),curCSV.getString(8),curCSV.getString(9),
curCSV.getString(10),curCSV.getString(11),curCSV.getString(12),curCSV.getString(13),curCSV.getString(14),
curCSV.getString(15),curCSV.getString(16),curCSV.getString(17),curCSV.getString(18),curCSV.getString(19)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
}
catch(SQLException sqlEx)
{
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}
catch (IOException e)
{
Log.e("MainActivity", e.getMessage(), e);
}
catch(NullPointerException n)
{
n.printStackTrace();
}
}