Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

copy database file to sdcard in android

I am getting my database file by this code

  File dbFile=getDatabasePath("EdsysEyfsDB.db");
               Log.v("database name checking", dbFile.toString());

I want to copy this database file to sdcard so I can do some operation for that. But I can't do any operation on that. The below code is using for copy to sd card

         if (dbFile.exists()) {
                       InputStream inStream = new FileInputStream(dbFile);
                       String file = Environment.getExternalStorageDirectory().getPath()
                            +"/" + "database.db";
                       Log.d("file name checking in  dbFilecondition", file);
                       FileOutputStream fs = new FileOutputStream(file);
                       byte[] buffer = new byte[1444];
                       while ((byteread = inStream.read(buffer)) != -1) {
                           bytesum += byteread;
                           fs.write(buffer, 0, byteread);
                       }
                       inStream.close();
                       fs.close();
                   }

But I am not going in this condition.The database file name is coming properly on LogCat. I already give permission for Read and Write file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this hope this helps you

public void exportDatabse(String databaseName) {
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+"";
                String backupDBPath = "backupname.db";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);

                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        } catch (Exception e) {

        }
    }

How to call

exportDatabse("YourDBName");

NOTE :

Remember to add permission to write to external storage with <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />, otherwise sd.canWrite() will be false.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...