尝试将数据库备份到SD卡时出现FileNotFoundException

时间:2012-12-15 00:42:39

标签: android

我正在尝试将我的数据库从我的应用程序备份到我的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

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

1 个答案:

答案 0 :(得分:4)

而不是:

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

尝试:

File dbFile = getDatabasePath(DATABASE_NAME);