如何备份存储在我的应用程序根目录中的图像

时间:2017-10-09 06:17:44

标签: android

在我的应用程序中,我捕获图像并将其存储在应用程序的根目录中。这些图片只能通过我的应用查看,不会在图库中查看。现在我需要像db备份一样备份这些映像。我怎样才能做到这一点?请帮帮我。

这是将图像存储在根文件夹中的代码:

private void createDirectoryAndSaveFile(Bitmap imageToSave) {
    File direct = new File(getFilesDir() + "/CAT_IMG/");
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
    String fileName = "fav" + timeStamp + ".JPG";
    if (!direct.exists()) {
       // File wallpaperDirectory = new File("/CAT_IMG");
        direct.mkdir();
    }

    File file = new File(direct, fileName);
    if (file.exists()) {
        file.delete();
    }
    try {
        FileOutputStream out = new FileOutputStream(file);
        imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这是备份db的代码:

    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String backupDBPath = String.format("%s.bak", DataProvider.DATABASE_NAME);

            String currentDBPath = "//data//" + getPackageName() + "//databases//" + databaseName + "";
            //   File currentDB = context.getDatabasePath(DataProvider.);
            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(getApplicationContext(), "Backup Successful!",
                Toast.LENGTH_SHORT).show();

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:0)

您的第一个代码是将JPEG图像保存到app目录,第二个代码是将数据库复制到备份位置。复制数据库文件与备份映像无关。

您必须将所有JPEG文件复制到其他位置

public void backup() {
    File direct = new File(getFilesDir() + "/CAT_IMG/");
    File backupDirect = new File(Environment.getExternalStorageDirectory() + "/backup/CAT_IMG/");
    for(File srcFile : direct.listFiles()) {
        if (srcFile.isFile() && srcFile.getName().endsWith(".JPG")) {
           File targetFile = packupDirect.getAbsolutePath() + "/" + srcFile.getName();
           copyFile(srcFile, targetFile);
        }
    }
}

private void copyFile(File src, File dest) {
    FileChannel sourceChannel = null;
    FileChannel destChannel = null;
    try {
        sourceChannel = new FileInputStream(src).getChannel();
        destChannel = new FileOutputStream(dest).getChannel();
        destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
    } finally {
        sourceChannel.close();
        destChannel.close();
    }
}

我没有测试过那些代码,但是这样的代码应该有用。

但请记住,StackOverflow实际上不是一个让人们编写代码的平台。