Android에서 데이터베이스 파일을 SD 카드에 어떻게 백업합니까?
SQLite 데이터베이스를 SD 카드에 자동으로 백업하는 기능을 Android 앱에 추가하고 싶습니다 .
이것에 대해 가장 좋은 방법은 무엇입니까? 사용 가능한 예제 또는 튜토리얼이 있습니까?
SQLite 데이터베이스는 완전히 독립적 인 파일이며 이동이 가능합니다. 전체 파일을 SD 카드에 바로 복사 할 수 있습니다.
먼저 SD 카드가 장치에 설치되어 있는지 확인하고 경로가 무엇인지 확인합니다 (사용 Environment.getExternalStorageDirectory()
).
이 코드는 저에게 효과적입니다!
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//{package name}//databases//{database name}";
String backupDBPath = "{database name}";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
}
이것이 루트가 아닌 전화에서 작동하는지 아는 사람이 있습니까? 나는 뿌리 G1에서만 시도했습니다.
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//"+ packageName +"//databases//"+dbList[0];
String backupDBPath = dbList[0];
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
"/"가 "\"인 위의 예와는 대조적으로 작동하지만 그것을 알아내는 데 내 인생의 20 분을 낭비했지만 실제로는 더 빨리 보았어야했습니다. 는 Toast
당신에게 파일이되었습니다 장소를 말하거나 작업을하지 않을 때 무엇이 잘못되었는지를 알려줍니다.
나는 대답 당신이 당신에 배치 할 수있는 방법이 유사한 질문을 SQLiteOpenHelper
. 일종의 외부 스토리지에서 내부 애플리케이션 스토리지로 db 파일을 복사하는 것만 큼 간단합니다. 또한 Android가 데이터베이스 호출을 수행 할 수있는 적절한 상태인지 확인하기 위해 db 파일을 열고 읽는 몇 가지 추가 코드가 있습니다.
public static void BackupDatabase() throws IOException
{
boolean success =true;
File file = null;
file = new File(Environment.getExternalStorageDirectory() +"/M.O.L.S_Backup");
if (file.exists())
{
success =true;
}
else
{
success = file.mkdir();
}
if (success)
{
String inFileName = "/data/data/com.sygic.sdk.demo/databases/MOLS_DB.s3db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/M.O.L.S_Backup/MOLS_DB.s3db";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
fis.close();
}
}
당신은 android.permission.WRITE_EXTERNAL_STORAGE
당신의 응용 프로그램 에서 권한을 부여 해야합니다. 루팅되지 않은 장치에서 잘 작동합니다.
전화가 루팅되었는지 여부는 알 수 없지만 파일을 다음 위치에 작성해야합니다.
/Android/data/{package_name}/files/
루팅 여부에 관계없이 작동합니다.
처음 사용하는 경우 데이터베이스 어댑터에서 데이터베이스 이름을 찾을 수 있습니다.
SharedPreferences에 대해서도이 작업을 수행 할 수 있지만 Context.MODE_PRIVATE를 Context.MODE_MULTI_PROCESS로 변경해야합니다.
SharedPreferences_name은 다음과 같아야합니다. = ExportSP("temp.xml");
String currentPathForSharedPreferences = "/data/"+ context.getPackageName() +"/shared_prefs/"+ SharedPreferences_name;
수출용
exportDB("MyDbName");
private void exportDB(String db_name){
File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +
File.separator + "Your Backup Folder"+
File.separator );
boolean success = true;
if (!sd.exists()) {
success = sd.mkdir();
}
if (success) {
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+ context.getPackageName() +"/databases/"+db_name;
String backupDBPath = db_name;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
} catch(IOException e) {
e.printStackTrace();
}
}}
수입 용
importDB("MyDbName");
private void importDB(String db_name){
File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +
File.separator + "Your Backup Folder"+
File.separator );
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String backupDBPath = "/data/"+ context.getPackageName() +"/databases/"+db_name;
String currentDBPath = db_name;
File currentDB = new File(sd, currentDBPath);
File backupDB = new File(data, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
} catch(IOException e) {
e.printStackTrace();
}
}
@skeniver의 코드 가 저에게 효과적입니다. 다음을 추가하고 싶습니다.
사용하다:
String currentDbPath = getApplicationContext().getDatabasePath("{database name}");
데이터베이스 경로를 제공합니다. 다음과 같이 경로를 하드 코딩하는 대신 사용하는 것이 좋습니다.
String currentDbPath = "//data//{package name}//databases//{database name}";
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//"+getPackageName()+"//databases//"+DATABASE_NAME+"";
String backupDBPath = "backup.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
'program story' 카테고리의 다른 글
HttpContext.Current에 액세스 할 수 없습니다. (0) | 2020.12.10 |
---|---|
http 라이브 스트리밍 m3u8 파일의 FFMPEG mp4? (0) | 2020.12.10 |
omniauth facebook 로그인을 팝업으로 전환 (0) | 2020.12.10 |
jQuery는 한 클래스를 다른 클래스로 바꿉니다. (0) | 2020.12.10 |
활동에서 조각이 생성되었을 때 null을 반환하는 getView (0) | 2020.12.10 |