将我的数据库移动到SD卡无法正常工作

时间:2012-11-13 13:15:39

标签: java android

我正在使用下面的代码尝试将我的数据库文件移动到我的SD卡。除了sd下的红线外,我没有任何问题。有任何想法吗?

File data = Environment.getDataDirectory();
if (sd.canWrite()) {
    String currentDBPath = "\\data\\application.package\\databases\\name";
    String backupDBPath = "name";
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    if (currentDB.exists()) {
        FileChannel src;
    try {
    src = new FileInputStream(currentDB).getChannel();
        FileChannel dst = new FileOutputStream(backupDB).getChannel();
        try {
        dst.transferFrom(src, 0, src.size());
    src.close();
            dst.close();
        } catch (IOException e) {                                                    
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    }

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

如果您创建了一个变量,则只能使用变量:

把它放在你的代码之前:

File sd = Environment.getExternalStorageDirectory();

答案 1 :(得分:0)

如果您使用的是SQLite数据库,请尝试以下方法:

public class _DBHelper extends SQLiteOpenHelper {

    public boolean backUp() throws Exception
        {
            InputStream input = null;
            OutputStream output = null;

            try {
                SQLiteDatabase db = this.getReadableDatabase();
                String strSource = db.getPath();

                String strDest = Utilities.getAppDocumentsFolder(_context) + "/"
                        + DATABASE_NAME;

                File fileDest = new File(strDest);
                if (fileDest.exists())
                {
                    fileDest.delete();
                }

                input = new FileInputStream(strSource);

                output = new FileOutputStream(strDest);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = input.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
            } catch (Exception e) {
                throw e;
            } finally
            {
                if (output != null)
                {
                    output.flush();
                    output.close();
                }
                if (input != null)
                {
                    input.close();
                }
            }

            return true;
        }
}