am a rookie. The present location of my app folder when installed is in data/data but I want to change the folder location(com.time.notes) to Android/data which is where alot of the folder of the apps I install shows, this is the code am presently trying.
public void backup(String item) {
OutputStream myOutput = null;
InputStream myInput = null;
File directory;
String databasePath = "/data/data/"+getPackageName()+"/databases/Memo.db";
File f = new File(databasePath);
if (f.exists()) {
try {
directory = new File("/mnt/sdcard/"+getResources().getString(R.string.app_name)+"/Backup");
if (!directory.exists())
directory.mkdir();
if (item.equals("Backup")) {
myOutput = new FileOutputStream(directory.getAbsolutePath() + File.separator + "/"+getResources().getString(R.string.app_name));
myInput = new FileInputStream(databasePath);
Toast.makeText(this, "Backup Location " + directory, Toast.LENGTH_LONG).show();
} else if (item.equals("Restore")) {
myInput = new FileInputStream(directory.getAbsolutePath() + File.separator + "/"+getResources().getString(R.string.app_name));
myOutput = new FileOutputStream(databasePath);
Toast.makeText(this, "Backup Restored Successfully ", Toast.LENGTH_LONG).show();
}
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
} catch (Exception e) {
} finally {
try {
if (myOutput != null) {
myOutput.close();
myOutput = null;
}
if (myInput != null) {
myInput.close();
myInput = null;
}
} catch (Exception e) {
}
}
}
}
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.
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;
}
}
When you use emulator your sqlite file is stored in a folder near your main application folder and you can download it. But this feature is not accessible in not rooted devices. How can I backup this existing sqlite file in SD Card programmatically?
I want to have a button in my application that stores this file in a special path in my SD Card. Is it possible?
Thanks,
You can try this, work for me, remember to get the WRITE_EXTERNAL_STORAGE permission in your manifest:
// Copy to sdcard for debug use
public static 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("/mnt/sdcard/DB_DEBUG");
if (!directory.exists())
directory.mkdir();
myOutput = new FileOutputStream(directory.getAbsolutePath()
+ "/" + DATABASE_NAME);
myInput = new FileInputStream(databasePath);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
} catch (Exception e) {
} finally {
try {
if (myOutput != null) {
myOutput.close();
myOutput = null;
}
if (myInput != null) {
myInput.close();
myInput = null;
}
} catch (Exception e) {
}
}
}
}
You can try following code,
String path = Environment.getExternalStorageDirectory().toString() + "/path";
File folder = new File( path );
if (!folder.exists())
{
folder.mkdirs();
}
File dbfile = new File( path + "/database.db" );
if ( !dbfile.exists() )
{
dbFile.createFile();
}
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
You can try this to copy a file:
public void copyFile(File in, File out) {
String DialogTitel = getString(R.string.daten_wait_titel);
String DialogText = getString(R.string.kopiervorgang_laeuft);
try {
// Dialogdefinition Prograssbar
final ProgressDialog dialog = new ProgressDialog(this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
dialog.setCancelable(false);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
dialog.show();
new Thread(new MyCopyThread(in, out)) {
#Override
public void run() {
try {
FileChannel inChannel = new FileInputStream(
MyCopyThread.in).getChannel();
FileChannel outChannel = new FileOutputStream(
MyCopyThread.out).getChannel();
try {
System.out.println("KOPIEREN");
inChannel.transferTo(0, inChannel.size(),
outChannel);
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
setCopyError(false);
} catch (IOException e) {
setCopyError(true);
// throw e;
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
dialog.dismiss();
// Abschlussarbeiten
if (useExternalSD == true) {
// Externe DB
moveDBtoExternFinish();
} else {
// Interne DB
moveDBtoInternFinish();
}
moveDBFinishHandler.sendMessage(moveDBFinishHandler
.obtainMessage());
} catch (Exception ex) {
}
}
}.start();
} catch (Exception exx) {
}
}
This is the code to get the filname of your internal db:
File interneDB = getApplicationContext().getDatabasePath(MY_DB_NAME);
Replace MY_DB_NAME with the name of your DB
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();
}
}