如何以编程方式将应用程序数据复制到android中的sdcard?

时间:2013-12-04 07:47:56

标签: android database sqlite

我正在做一个应用来备份和恢复Android设备中所有用户安装的应用程序。我能够备份用户选择备份的所有应用的apk文件。现在我必须备份应用程序的数据文件以及apk文件。

我正在尝试这样的事情

public void copyDbToSdcard(String packageName) {
    InputStream myInput;
    String dbpath = "/data/"+packageName+"/databases/";
    String sdpath = Environment.getExternalStorageDirectory().getPath();

    try {

        File exist=new File(Environment.getDataDirectory()+dbpath);
        System.out.println("1 "+ exist.exists());

        // Set the output folder on the Scard
        File directory = new File(sdpath + "/Back");
        // Create the folder if it doesn't exist:
        if (!directory.exists()) {
            directory.mkdirs();
        }
        // Set the output file stream up:
        myInput = new FileInputStream(Environment.getDataDirectory()
                + dbpath);

        OutputStream myOutput = new FileOutputStream(directory.getPath()
                + "/refuel_db");

        // Transfer bytes from the input file to the output file
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);    
        }
        // Close and clear the streams

        myOutput.flush();

        myOutput.close();

        myInput.close();

        Toast.makeText(MainActivity.this, "Backup Done Succesfully!", Toast.LENGTH_LONG)
                .show();

    } catch (FileNotFoundException e) {


        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {

        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

我收到错误日志

EACCES (Permission denied)在线

myInput = new FileInputStream(Environment.getDataDirectory()+ dbpath);

我已经在清单文件中提供了READ和WRITE权限

3 个答案:

答案 0 :(得分:0)

尝试使用

中的/sdcard
String dbpath = "/sdcard/"+packageName+"/databases/";

而不是/ data,因为它属于“内部存储”。

答案 1 :(得分:0)

试试这个

String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + dbpath);

并将其添加到您的清单文件

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

希望它有助于:)

答案 2 :(得分:0)

private static String audioFilePath;

布局布局

之后
audioFilePath =Environment.getExternalStorageDirectory().getAbsolutePath() + "/abcd";
File abcd=new File(audioFilePath);
abcd.mkdirs();

为您的问题..........

但你应该用SD卡的名字命名为abcd