Ive seen a few posts on how to import and export a database in android and i found these code, but i cant seem to make it work. I get the error java.io.filenotfoundexception /storage/sdcard0/BackupFolder/DatabaseName:open failed ENOENT (no such file or directory). Ive changed a few things but i still get no file found exception
here is my export:
private void exportDB() {
try {
db.open();
File newFile = new File("/sdcard/myexport");
InputStream input = new FileInputStream(
"/data/data/com.example.mycarfuel/data
bases/MyDatabase");
OutputStream output = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
db.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and my import:
private void importDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//" + "PackageName"
+ "//databases//" + "DatabaseName";
String backupDBPath = "/BackupFolder/DatabaseName
";
File backupDB = new File(data, currentDBPath);
File currentDB = 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(getBaseContext(), backupDB.toString(),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
}
SQlite database to our local file system-
Function declaration-
try {
backupDatabase();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Function defined-
public static void backupDatabase() throws IOException {
//Open your local db as the input stream
String inFileName = "/data/data/com.myapp.main/databases/MYDB";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/MYDB";
//Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
output.write(buffer, 0, length);
}
//Close the streams
output.flush();
output.close();
fis.close();
}
Above accepted answer will not work for Android version on or above 6 because database path is different.
please check below code . It will work on all devices.
public static boolean exportDB(Context context) {
String DATABASE_NAME = "my.db";
String databasePath = context.getDatabasePath(DATABASE_NAME).getPath();
String inFileName = databasePath;
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory() + "/" + DATABASE_NAME;
OutputStream output = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
//Close the streams
output.flush();
output.close();
fis.close();
return true;
} catch (Exception e) {
return false;
}
}
Related
i want to copy file from asset to other application data directory.i have also given root acess to it.but this code doesn't work.its work on extenal storage directory .but not copy file in data directory..
public void onClick(View arg1){
String command[] = { "su", "-c", "ls", "/data" };
Shell shell = new Shell();
String text = shell.sendShellCommand(command);
if (new File((Object)Environment.getDataDirectory() + "/data/com.my/shared_pref/com.myxml").exists()) {
Toast.makeText(getApplicationContext(),"copied",Toast.LENGTH_LONG).show();
MainActivity.this.copyAssets();
}
else{
Toast.makeText(getApplicationContext(),"error! copy failed ",Toast.LENGTH_LONG).show();
private void copyAssets()
{
AssetManager assetManager = getAssets();
String[] files = null;
InputStream in = null;
OutputStream out = null;
String filename =
"com.my.xml" ;
try
{
in = assetManager.open( filename);
out = new FileOutputStream((Environment.getDataDirectory().toString() +"/data/com.my/shared_pref/" + filename));
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (IOException e)
{
Log. e ( "tag" , "Failed to copy asset file: " , e);
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
if anyone knows how to do it?
Pleaase suggest me.!!
Thanks.!!
This is exactly what you need. This code copies sample.apk from assets to the application data directory. You can change the path to anywhere you want.
private String copyAssets() {
AssetManager assetManager = getActivity().getAssets();
InputStream in = null;
OutputStream out = null;
String filename = "sample.apk";
String path = Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getActivity().getPackageName()
+ "/files";
try {
in = assetManager.open("files/" + filename);
File outFile = new File(path);
if (!outFile.exists()) {
outFile.mkdirs();
}
out = new FileOutputStream(outFile + "/" + filename);
copyFile(in, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return path + "/" + filename;
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
Use this code. I used this code in my project, Got it on net somewhare, it works.
private void copyDataBase() throws IOException
{
//Open your local db as the input stream
InputStream myInput = _context.getAssets().open(DB_NAME);
// Path to db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0)
{
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
I'm using Intent to export my .db file to the google drive. and import the .db file through the local folder on the device.
how can i import the file to my device from drive again?
what is the best way to "backup" the .db file and import the file?
it's possible to do that action without using "google drive api"?
Help me please !
public class BackUpDb {
Context context;
public BackUpDb(Context activity) {
this.context = activity;
}
public void exportDb(){
File direct = new File(Environment
.getExternalStorageDirectory()
+ "/folderToBeCreated");
if (!direct.exists()) {
if (direct.mkdir()) {
// directory is created;
}
}
try {
exportDB();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void importDb(){
importDB();
}
// importing database
#SuppressLint("SdCardPath")
private void importDB() {
try {
// File file = getBaseContext().getFileStreamPath(Environment.getExternalStorageDirectory()
// + "/MyDatabase");
// if(file.exists()){
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory()
+ "/folderToBeCreated/MyDatabase");
String outFileName = "/data/data/com.example.application/databases/"+DbHandler.DB_NAME;
OutputStream output = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
Toast.makeText(context, "Ok :)",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(context, "No list found",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#SuppressLint("SdCardPath")
private void exportDB() throws IOException {
// Open your local db as the input stream
try {
String inFileName = "/data/data/com.example.application/databases/"+DbHandler.DB_NAME;
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+ "/folderToBeCreated/MyDatabase";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG)
.show();
}
Toast.makeText(context,
"save to :\n/folderToBeCreated",Toast.LENGTH_LONG).show();
}
public void sendDb(String mailAddres){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("application/octet-stream");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {mailAddres});
intent.putExtra(Intent.EXTRA_SUBJECT, "MyDatabase");
File root = Environment.getExternalStorageDirectory();
File file = new File(root, "/folderToBeCreated/MyDatabase");
if (!file.exists() || !file.canRead()) {
Toast.makeText(context, "No sd-card", Toast.LENGTH_SHORT).show();
return;
}
Uri uri = Uri.parse("file://" + file.getAbsolutePath());
intent.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(intent, "BACKUP"));
}
}
Since, Android 4.4 (KitKat), the ability to create files on external SD cards has been removed.
I am trying to copy a database named "adinpect" from the asset folder to the application databases folder, but it is not working...
Code (in main activity onCreate(), just for testing):
try {
String destPath = "/data/data/" + getPackageName() + "/databases";
File f = new File(destPath);
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
//---copy the db from the assets folder into the databases folder---
CopyDB(getBaseContext().getAssets().open("adinspect"), new FileOutputStream(destPath + "/adinspect"));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}//end copyDB
The "databases" folder is created but there in nothing in it, trying to access it by DDMS.
I do not get any errors.
Any suggestion?
Thanks
This code wlll help you to copy DB from assets folder.
You can check first if DB exists or not.
try{
// CHECK IS EXISTS OR NOT
SQLiteDatabase dbe = SQLiteDatabase.openDatabase("/data/data/"+getPackageName+"/databases/dbname.sqlite",null, 0);
dbe.close();
}
catch(Exception e)}
{
// COPY IF NOT EXISTS
AssetManager am = getApplicationContext().getAssets();
OutputStream os = new FileOutputStream("/data/data/"+getPackageName+"/databases/dbname.sqlite");
byte[] b = new byte[100];
int r;
InputStream is = am.open("dbname.sqlite");
while ((r = is.read(b)) != -1) {
os.write(b, 0, r);
}
is.close();
os.close();
}
I have been trying to export my database file into the external memory of my android phone by using
private final String DB_NAME = "MemberData";
private final String TABLE_NAME = "MemberDB";
//Get a reference to the database
File dbFile = this.getDatabasePath(DB_NAME);
//Get a reference to the directory location for the backup
File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File backup = new File(exportDir, dbFile.getName());
//Check the required operation String command = params[0];
//Attempt file copy
try {
backup.createNewFile();
fileCopy(dbFile, backup);
} catch (IOException e) {
/*Handle File Error*/
}
private void fileCopy(File source, File dest) throws IOException {
FileChannel inChannel = new FileInputStream(source).getChannel();
FileChannel outChannel = new FileOutputStream(dest).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
It managed to create a directory name "myappsbackup" but my database couldnt be copied over. it is always size 0 and my tables are missing. Is there something wrong with my method of copying?
Here is the code I use to write or backup my SQLite db to the sdcard.
try {
db.open();
File newFile = new File("/sdcard/Your File Name Here");
InputStream input = new FileInputStream(
"/data/data/com.packageNameHere/databases/DB Name Here");
OutputStream output = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
db.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm desperately trying to copy a file to the sdcard from my raw folder, but it won't work! The file just doesn't show up in the file manager, and the program I give the path to (via an intent) can't find it either. This is what I'm trying...
private void CopyAssets() throws IOException {
String path = Environment.getExternalStorageDirectory() + "/jazz.pdf";
InputStream in = getResources().openRawResource(R.raw.jazz);
FileOutputStream out = new FileOutputStream(path);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
}
After which I try...
try {
CopyAssets();
} catch (IOException e1) {
e1.printStackTrace();
}
String aux = Environment.getExternalStorageDirectory() + "/jazz.pdf";
Uri path = Uri.parse(aux);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(bgn1.this, "No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
Just write out.flush(); in finally block and let me know what happen,
finally {
out.flush();
in.close();
out.close();
}
Update:
Working code:
private void CopyAssets() throws IOException
{
InputStream myInput = getResources().openRawResource(R.raw.jazz);
String outFileName = Environment.getExternalStorageDirectory() + "/jazz.pdf";
OutputStream myOutput = new FileOutputStream(outFileName);
// 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 the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
}