2013-08-16 2 views
0

내 애플 리케이션 데이터베이스가 있습니다. 이제 백업용 데이터베이스를 표준 사용자 폴더 또는 SD 카드에 복사하려고합니다. 이클립스에서 나는 그것을 data/data/database에서 찾았다 - 그러나 실제 장치의 데이터베이스는 어디에 있는가?안드로이드 데이터베이스에 액세스하는 방법

답변

0

시도해주세요. 그냥 lite.db를 바꾸십시오. 내 데이터베이스의 이름입니다.

private void copyDB() { 
    File dir = new File(Environment.getExternalStorageDirectory() 
      + "/backup"); 
    if (!dir.exists()) { 
     dir.mkdirs(); 
    } 
    File from = new File("/data/data/" + getPackageName() + "/databases/", 
      "lite.db"); 
    File to = new File(dir, "lite.db"); 
    try { 
     FileInputStream in = new FileInputStream(from); 
     FileOutputStream out = new FileOutputStream(to); 
     FileChannel fromChannel = null, toChannel = null; 
     try { 
      fromChannel = in.getChannel(); 
      toChannel = out.getChannel(); 
      fromChannel.transferTo(0, fromChannel.size(), toChannel); 
     } finally { 
      if (fromChannel != null) 
       fromChannel.close(); 
      if (toChannel != null) 
       toChannel.close(); 
     } 
    } catch (IOException e) { 
     Log.e("backup", "Error backuping up database: " + e.getMessage(), e); 
    } 

} 

또한 권한을 추가하는 것을 잊지 :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
0

이클립스가 보여주는 경로가 맞다. 절대 경로가 장치별로 변경된다. 장치를 루팅했다면 파일을 볼 수있다. 항상/data/data/*에 있습니다. 장치가 루팅되지 않은 경우이 파일을 볼 수 없습니다.

0

IN REAL 장치 이러한 파일에 액세스 할 수 없습니다 !!!

+0

그게 잘못입니다. 탐색기에서 디렉토리에 액세스 할 수는 없지만 프로그래밍 방식으로 액세스 할 수 있습니다. – Namenlos

+0

물론 루트 권한이있는 경우에만 확인하십시오.이 내용을 확인하십시오. http://stackoverflow.com/questions/7268908/access-the-phone-internal-storage-to-push-in-sqlite-database-file – Exceptional

+0

You 루트 권한 없이도 액세스 할 수 있습니다. 내 대답 좀 봐. – Namenlos

0

데이터베이스는 장치 데이터 디렉토리에 저장됩니다, 당신은 Environment.getDataDirectory() 그것을 얻을 수 있습니다. 이 디렉토리에서 데이터베이스는 /data/YOUR.PACKAGE.NAME/databases/YOUR.DB.NAME 경로에 저장됩니다. 물론

public void exportDB() { 
    try { 
     File sd = Environment.getExternalStorageDirectory(); 
     File data = Environment.getDataDirectory(); 
     if(sd.canWrite()) { 
      String currentDBPath = "//data//com.example.packagename//databases//" + DB_NAME; 
      String backupDBPath = DB_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) { 
     e.printStackTrace(); 
    } 
} 

, 당신은 또한 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

그 후, 당신은에 의해 주어진 파일 이름으로 당신의 SD에 데이터베이스를 찾을 수 있습니다 필요 여기

는 데이터베이스가 어떻게 백업 할 수있는 약간의 예입니다 "DB_NAME".

+0

@ Namenlos와 코드에 모래가있어 주셔서 감사합니다. –

관련 문제