1

我正在尝试将我的数据库从我的应用程序备份到我的 sd 卡,但每次我尝试我得到 FileNotFoundException并且我不知道为什么当数据库的名称是正确的

备份数据库的代码

try{
        File dbFile = new File(Environment.getDataDirectory() + "/data/my.app.package/databases/Games.db");
        File exportDir = new File(Environment.getExternalStorageDirectory()+"/BCAData");
           if (!exportDir.exists()) {
              exportDir.mkdirs();
           }
           File file = new File(exportDir, dbFile.getName());

           file.createNewFile();
           FileChannel inChannel = new FileInputStream(dbFile).getChannel();  //fails here
           FileChannel outChannel = new FileOutputStream(file).getChannel();
           try {
              inChannel.transferTo(0, inChannel.size(), outChannel);
           } finally {
              if (inChannel != null)
                 inChannel.close();
              if (outChannel != null)
                 outChannel.close();
           }
    }catch(Exception e){
        e.printStackTrace();
    }

在我的内容提供商中,我有这样的数据库名称

private static final String DATABASE_NAME = "Games";
private static final String GAMES_TABLE = "Games";

错误:

12-14 19:38:38.313: W/System.err(10452): java.io.FileNotFoundException: /data/data/com.tyczj.bowling/databases/Games.db: open failed: ENOENT (No such file or directory)
12-14 19:38:38.313: W/System.err(10452):    at libcore.io.IoBridge.open(IoBridge.java:416)
12-14 19:38:38.313: W/System.err(10452):    at java.io.FileInputStream.<init>(FileInputStream.java:78)
12-14 19:38:38.323: W/System.err(10452):    at com.tyczj.bowling.services.DatabaseExportService.onHandleIntent(DatabaseExportService.java:27)
12-14 19:38:38.323: W/System.err(10452):    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
12-14 19:38:38.333: W/System.err(10452):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-14 19:38:38.333: W/System.err(10452):    at android.os.Looper.loop(Looper.java:137)
12-14 19:38:38.343: W/System.err(10452):    at android.os.HandlerThread.run(HandlerThread.java:60)
12-14 19:38:38.343: W/System.err(10452): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
12-14 19:38:38.353: W/System.err(10452):    at libcore.io.Posix.open(Native Method)
12-14 19:38:38.353: W/System.err(10452):    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
12-14 19:38:38.353: W/System.err(10452):    at libcore.io.IoBridge.open(IoBridge.java:400)
12-14 19:38:38.353: W/System.err(10452):    ... 6 more

我不明白为什么这是错误的路径,所以这不是数据库的名称?

4

1 回答 1

4

代替:

File dbFile = new File(Environment.getDataDirectory() + "/data/my.app.package/databases/Games.db");

尝试:

File dbFile = getDatabasePath(DATABASE_NAME);
于 2012-12-15T00:46:23.107 回答