Is it possible to copy a database file to an SD card?

I have a database on my Android phone and I need to get the information on the SD card.

Can I save the database file to the SD card in a readable state? I could not find any information on how to do this.

The source code that copies the database file to the SD card would be ideal.

+1
source share
2 answers

The database file is like any other file, if you make a copy of the binary, it will work.

There is no built-in method for copying files in Java, so you can use this:

Standard compressed way to copy a file in Java?

SD-:
SD-

+2

script SO. , Android, , adb, !

( ​​ ) - : " , :/storage/emulated/0/DB-DEBUG/todotable.db", shell : "/storage/emulated/legacy/DB-DEBUG/"... , , sqlite!

//db will reside in: /storage/emulated/legacy/DB_DEBUG
private void copyDatabase(Context c, String DATABASE_NAME) {
    String databasePath = c.getDatabasePath(DATABASE_NAME).getPath();
    File f = new File(databasePath);
    OutputStream myOutput = null;
    InputStream myInput = null;
    Log.d("testing", " testing db path " + databasePath);
    Log.d("testing", " testing db exist " + f.exists());

    if (f.exists()) {
        try {
            File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DB-DEBUG");
            if (!directory.exists()){
                directory.mkdir();
            }

            String copyPath = directory.getAbsolutePath() + "/" + DATABASE_NAME;
            myOutput = new FileOutputStream(copyPath);
            myInput = new FileInputStream(databasePath);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }

            myOutput.flush();
            Toast.makeText(getBaseContext(), "Your database copied to: " + copyPath, Toast.LENGTH_LONG).show();
            Log.d("testing", " database saved to: " + copyPath);

        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();

        } finally {
            try {
                if (myOutput != null) {
                    myOutput.close();
                    myOutput = null;
                }
                if (myInput != null) {
                    myInput.close();
                    myInput = null;
                }
            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    }
}
0

All Articles