I am trying to implement a simple SQLite export/import for backup purposes. Export is just a matter of storing a copy of the raw current.db file. What I want to do for import is to just delete the old current.db file and rename the imported.db file to current.db. Is this possible? When I try this solution, I get the following error:
06-30 13:33:38.831: ERROR/SQLiteOpenHelper(23570):
android.database.sqlite.SQLiteDatabaseCorruptException: error code 11: database disk image is malformed
If I look at the raw database file in a SQLite browser it looks fine.
I use this code in the SQLiteOpenHelper in one of my applications to import a database file.
EDIT: I pasted my FileUtils.copyFile() method into the question.
SQLiteOpenHelper
public static String DB_FILEPATH = "/data/data/{package_name}/databases/database.db";
/**
* Copies the database file at the specified location over the current
* internal application database.
* */
public boolean importDatabase(String dbPath) throws IOException {
// Close the SQLiteOpenHelper so it will commit the created empty
// database to internal storage.
close();
File newDb = new File(dbPath);
File oldDb = new File(DB_FILEPATH);
if (newDb.exists()) {
FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
// Access the copied database so SQLiteHelper will cache it and mark
// it as created.
getWritableDatabase().close();
return true;
}
return false;
}
FileUtils
public class FileUtils {
/**
* Creates the specified <code>toFile</code> as a byte for byte copy of the
* <code>fromFile</code>. If <code>toFile</code> already exists, then it
* will be replaced with a copy of <code>fromFile</code>. The name and path
* of <code>toFile</code> will be that of <code>toFile</code>.<br/>
* <br/>
* <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
* this function.</i>
*
* #param fromFile
* - FileInputStream for the file to copy from.
* #param toFile
* - FileInputStream for the file to copy to.
*/
public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = fromFile.getChannel();
toChannel = toFile.getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
try {
if (fromChannel != null) {
fromChannel.close();
}
} finally {
if (toChannel != null) {
toChannel.close();
}
}
}
}
}
Don't forget to delete the old database file if necessary.
This is a simple method to export the database to a folder named backup folder you can name it as you want and a simple method to import the database from the same folder a
public class ExportImportDB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//creating a new folder for the database to be backuped to
File direct = new File(Environment.getExternalStorageDirectory() + "/Exam Creator");
if(!direct.exists())
{
if(direct.mkdir())
{
//directory is created;
}
}
exportDB();
importDB();
}
//importing database
private void importDB() {
// TODO Auto-generated method stub
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();
}
}
//exporting database
private void exportDB() {
// TODO Auto-generated method stub
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath= "//data//" + "PackageName"
+ "//databases//" + "DatabaseName";
String backupDBPath = "/BackupFolder/DatabaseName";
File currentDB = new File(data, currentDBPath);
File backupDB = 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();
}
}
}
Dont forget to add this permission to proceed it
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>
Enjoy
To export db rather it is SQLITE or ROOM:
Firstly, add this permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Secondly, we drive to code the db functions:
private void exportDB() {
try {
File dbFile = new File(this.getDatabasePath(DATABASE_NAME).getAbsolutePath());
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = DirectoryName + File.separator +
DATABASE_NAME + ".db";
// 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 (IOException e) {
Log.e("dbBackup:", e.getMessage());
}
}
Create Folder on Daily basis with name of folder is Current date:
public void createBackup() {
sharedPref = getSharedPreferences("dbBackUp", MODE_PRIVATE);
editor = sharedPref.edit();
String dt = sharedPref.getString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));
if (dt != new SimpleDateFormat("dd-MM-yy").format(new Date())) {
editor.putString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));
editor.commit();
}
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "BackupDBs");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
DirectoryName = folder.getPath() + File.separator + sharedPref.getString("dt", "");
folder = new File(DirectoryName);
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
exportDB();
}
} else {
Toast.makeText(this, "Not create folder", Toast.LENGTH_SHORT).show();
}
}
Assign the DATABASE_NAME without .db extension and its data type is string
Import and Export of a SQLite database on Android
Here is my function for export database into device storage
private void exportDB(){
String DatabaseName = "Sycrypter.db";
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+ "com.synnlabz.sycryptr" +"/databases/"+DatabaseName ;
String backupDBPath = SAMPLE_DB_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Your Database is Exported !!", Toast.LENGTH_LONG).show();
} catch(IOException e) {
e.printStackTrace();
}
}
Here is my function for import database from device storage into android application
private void importDB(){
String dir=Environment.getExternalStorageDirectory().getAbsolutePath();
File sd = new File(dir);
File data = Environment.getDataDirectory();
FileChannel source = null;
FileChannel destination = null;
String backupDBPath = "/data/com.synnlabz.sycryptr/databases/Sycrypter.db";
String currentDBPath = "Sycrypter.db";
File currentDB = new File(sd, currentDBPath);
File backupDB = new File(data, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Your Database is Imported !!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want this in kotlin . And perfectly working
private fun exportDbFile() {
try {
//Existing DB Path
val DB_PATH = "/data/packagename/databases/mydb.db"
val DATA_DIRECTORY = Environment.getDataDirectory()
val INITIAL_DB_PATH = File(DATA_DIRECTORY, DB_PATH)
//COPY DB PATH
val EXTERNAL_DIRECTORY: File = Environment.getExternalStorageDirectory()
val COPY_DB = "/mynewfolder/mydb.db"
val COPY_DB_PATH = File(EXTERNAL_DIRECTORY, COPY_DB)
File(COPY_DB_PATH.parent!!).mkdirs()
val srcChannel = FileInputStream(INITIAL_DB_PATH).channel
val dstChannel = FileOutputStream(COPY_DB_PATH).channel
dstChannel.transferFrom(srcChannel,0,srcChannel.size())
srcChannel.close()
dstChannel.close()
} catch (excep: Exception) {
Toast.makeText(this,"ERROR IN COPY $excep",Toast.LENGTH_LONG).show()
Log.e("FILECOPYERROR>>>>",excep.toString())
excep.printStackTrace()
}
}
Related
Well, I'm trying to create a folder in my internal storage.
I have watched some tutorial but it's not working at all.
private void createDir() {
String folderName;
folderName = "myFolder";
File file = new File(Environment.getExternalStorageDirectory(), folderName);
if(!file.exists()){
file.mkdir();
Toast.makeText(getContext(),"Successful", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(),"Folder already exist", Toast.LENGTH_SHORT).show();
}
}
This is my method to create the new directory.
When I launch it, I receive the Toast "Successful" all the time.
But the directory is never created.
Just below the code for the permissions.
if(!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.SEND_SMS)){
String[] permissions = {Manifest.permission.WRITE_CALL_LOG,Manifest.permission.SEND_SMS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_SMS};
ActivityCompat.requestPermissions(getActivity(),permissions,1);
}else{
lay_dataset1=view.findViewById(R.id.lay_dataset1);
messagePerm();
}
Here my manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Can someone explain what is happening :)
EDIT :
private void copyAssets() {
AssetManager assetManager = getContext().getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getContext().getExternalFilesDir(null).getParent().replace("files","myfolder"), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, 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);
}
}
I tried this, I was able to move files that were in my "asset" folder at the same level as the "files" directory so why shouldn't I have the right to create a folder in this same location ?
At the first time you run your application, the app external storage directory
at Android/data/<package.name>/files is not created until you call this method getExternalFilesDir(null) Twice.
So try this code..
//Essential for creating the external storage directory for the first launch
getExternalFilesDir(null);
/*
output->> /storage/emulated/0/Android/data/<package.name>/files
*/
Log.i("HINT",getExternalFilesDir("").getAbsolutePath());
//Or create your custom folder
File outFile = new File(getExternalFilesDir(null).getParent(),"myfolder");
//make it as it is not exists
outFile.mkdirs();
/*
output->> /storage/emulated/0/Android/data/<package.name>/myfolder
*/
Log.i("HINT",outFile.getAbsolutePath());
this is my code for copying database from asset folder to SD card:
File databaseFile = new File(context.getExternalFilesDir(null),"");
if(!databaseFile.exists()){
databaseFile.mkdirs();
}
String outFileName = context.getExternalFilesDir(null) + "/db.db";
try {
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = context.getAssets().open("db");
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
} catch (Exception e) {
Log.v("this",e.getMessage().toString());
}
when I run it ,it gives me this error :
/storage/emulated/0/Android/data/myPackageName/files/db.db: open failed: EISDIR (Is a directory)
How can I solve this ?
I've read this topic but didn't work :
FileOutputStream crashes with "open failed: EISDIR (Is a directory)" error when downloading image
also ,I test it on read device, the same error
thank you
I cannot get the full picture from the log line you have attached.
Still, if I had to guess, your problem is probably here:
if(!databaseFile.exists()){
databaseFile.mkdirs();
}
Remember: mkdirs() takes the entire path param you pass it, breaks it and, if needed, creates new folders.
mkdirs() cannot tell a file from a directory
So, if you invoke it like this:
databaseFile.mkdirs("/sdcard/rootDir/resDir/myImage.png");
It will create a folder named myImage.png.
Please check your code and change if needed.
This is the code I'm using to copy all files in assets to a sdcard. It's a asynch task so you want to implement some kind of respond method to know when the code is done and the db is useable.
The variable maindir is the folder location that you're copying to
and remember to give promissions in manifest file
public class copyEveStaticDataDump extends AsyncTask<String,Void,String> {
private Context context;
private String url,filename;
private String maindir;
public copyEveStaticDataDump(Context contextt,String maindir) {
super();
this.context = contextt;
this.maindir = maindir;
}
#Override
protected String doInBackground(String... params) {
copyFilesToSdCard();
return null;
}
private void copyFilesToSdCard() {
copyFileOrDir(""); // copy all files in assets folder in my project
}
private void copyFileOrDir(String path) {
AssetManager assetManager = context.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = maindir;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
copyFileOrDir( p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = context.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+filename);
in = assetManager.open(filename);
if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file
newFileName = maindir + filename.substring(0, filename.length()-4);
else
newFileName = maindir+"/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
I am working on a Spying application for my college project purpose. For that i have logged the Calls, Location and SMS of the device and stored them in a database. Now i want to export the contents of the database to a text file.. I tried the below code.
private void readAndWriteCallsData() {
File dataBaseFile = getDatabasePath("DATABASE");
File callDataFile = new File(Environment.getDataDirectory()+"/data/com.example.myapp/databases/"+"DATABASE");
try {
BufferedReader dbFileReader = new BufferedReader(new FileReader(callDataFile));
String eachLine;
while((eachLine = dbFileReader.readLine()) != null)
{
Callslog.append(eachLine);
Callslog.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
But that is not working... Please help me...
You can encode the database file from binary stream to character stream by Base64, then decode the text when nessesary.
First find a Base64 library. You can use http://sourceforge.net/projects/iharder/files/base64/. There's only one file, "Base64.java".
Code example:
private void readAndWriteCallsData() {
File callDataFile = new File(Environment.getDataDirectory()+"/data/com.example.myapp/databases/"+"DATABASE");
try {
FileInputStream fis = new FileInputStream(callDataFile);
try{
byte[] buf = new byte[512];
int len;
while((len = fis.read(buf)) > 0){
String text = Base64.encodeBytes(buf, 0, len); // encode binary to text
Callslog.append(text);
Callslog.append("\n");
}
}finally{
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
To revert it, code like following:
private void revertCallsData() {
File encodedCallDataFile; // get reference to the encoded text file
try {
BufferedReader br = new BufferedReader(new FileReader(encodedCallDataFile));
try{
String line;
while((line = br.readLine()) != null){
byte[] bin = Base64.decode(line); // decode each line to binary, you can get the original database file
}
}finally{
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
ok guys after a lot of hit and trial i finally found the solution, here is the code, i saved the functionality in a button.
final String SAMPLE_DB_NAME = "MyDBName.db";//database name
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+ "your package name" +"/databases/"+SAMPLE_DB_NAME;
String backupDBPath = SAMPLE_DB_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(getApplicationContext(),"Your database has been exported",
Toast.LENGTH_LONG).show();
} catch(IOException e) {
e.printStackTrace();
}
}
});
the database will be saved in /storage/emulated/0/
I would recommend to export into a structered file format such as JSON or CSV. Here is my JSON exporter method. Maybe it helps
private static final String LOG_FOLDER = "/ExportFolder";
private static final String FILE_NAME = "export_file.json";
public static void exportMeasurementsJSON(Handler mHandler) {
sendToastMessage("Export to JSON started", mHandler);
File folder = new File(Environment.getExternalStorageDirectory()
+ LOG_FOLDER);
if (!folder.exists())
folder.mkdir();
final String filename = folder.toString() + "/"
+ getLogFileName(".json");
try {
FileWriter fw = new FileWriter(filename, false /* append */);
// get the db
SomeDateSource db = PIApplication.getDB();
// Google Gson for serializing Java Objects into JSON
Gson mGson = new GsonBuilder().create();
Cursor c = db.getAllRows();
if (c != null) {
while (c.moveToNext()) {
fw.append(mGson.toJson(new DBEntry(c
.getString(1), c.getString(2), c
.getDouble(3), c.getLong(4))));
fw.append('\n');
}
c.close();
}
fw.close();
sendToastMessage("Export finished", mHandler);
} catch (Exception e) {
sendToastMessage("Something went wrong", mHandler);
e.printStackTrace();
}
}
If you're interested I can also add my CSV exporter.
Your question is not that clear (Are you trying to copy the file to an alternative location or export the actual data from it?)
If you only wish to copy the file, you can copy the db file using the following method:
public static void copyFile(String sourceFileFullPath, String destFileFullPath) throws IOException
{
String copyFileCommand = "dd if=" + sourceFileFullPath + " of=" + destFileFullPath;
Runtime.getRuntime().exec(copyFileCommand);
}
Simply call that method with your database file path (/data/data/package_name/databases/database_name) as sourceFileFullPath and your target file path as destFileFullPath. You can than use tools such as SQLite Expert to view the content of the database on your PC/Laptop.
If your intention is to export the data from the database and store it in a text file (a CSV file or anything similar), then you should not read the database file content, and instead use the SQLiteDatabase class to query each table contents into a Cursor and iterate it to write each cursor row into a text file.
You could export the entire db into your sdcard folder and then use SQLite manager to open and see it's content.
A Example is available here: http://www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/
Here is the complete method for writing the Database in the SD Card:
/**
* Copy the app db file into the sd card
*/
private void backupDatabase(Context context) throws IOException {
//Open your local db as the input stream
String inFileName = "/data/data/yourappPackageName/databases/yourDBName.db";
// OR use- context.getFilesDir().getPath()+"/databases/yourDBName.db";//
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/"+SQLiteDataHelper.DB_NAME;
//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();
}
Hope it will help you.
One way to do this (I assume its a long procedure, easy one though), if you know the database and get all the tables and retrieve info from those tables. Since, we are talking about sqlite DBs, I assume it will be small.
SELECT * FROM dbname.sqlite_master WHERE type='table';
Following is the code which I use to copy a folder containing a txt file. The folder resides in assets folder of my application. While I copy , I get File not found exception in the line out = new FileOutputStream(newFileName);
I get this working perfectly, when I save this to /data/data folder; ie; internal memory. I have checked the SD card state and it shows mounted.
public class CpyAsset extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
copyFileOrDir("edu1");//directory name in assets
}
File sdCard = Environment.getExternalStorageDirectory();
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
File dir = new File (sdCard.getAbsolutePath());
if (!dir.exists()){
System.out.println("Created directory"+sdCard.getAbsolutePath());
boolean result = dir.mkdir();
System.out.println("Result of directory creation"+result);
}
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
System.out.println("Exception in copyFileOrDir"+ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = sdCard.getAbsolutePath() + "/"+filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
System.out.println("Exception in copyFile"+e);
}
}
}
Exception
01-01 06:13:34.783: INFO/System.out(11334): Exception in copyFilejava.io.FileNotFoundException: /mnt/sdcard/edu1/anees.txt: open failed: ENOENT (No such file or directory)
The folder(and the content) I try to copy is in assets/edu1/abc.txt
Can someone please let me know what causes this as I cannot find any obvious reasons for the same? Any help is much appreciated.
You are always trying to create the external storage root dir in this part:
File dir = new File (sdCard.getAbsolutePath());
if (!dir.exists()){
System.out.println("Created directory"+sdCard.getAbsolutePath());
boolean result = dir.mkdir();
System.out.println("Result of directory creation"+result);
}
so you are not creating the folder edu1/ and the creation of the file anees.txt in that folder will fail.
in your code you check if the sdcard path is exist while you should check for your path which result in the dir "edu1" is never created try use this instead
File dir = new File (sdCard.getAbsolutePath()+"/"+path);
Try it out this way.......
File f = new File("/sdcard/assets/edu1/abc.txt");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
I'm copying my db file to sd car using this methode please tell me if file at sdcard is already existing then whether it will replace or will not copy?
public boolean copyDbToSDCard() {
boolean success = false;
String SDCardPath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
final String DBPATH = SDCardPath + "/BD/";
final String DBNAME = "Mydb3.db";
this.getReadableDatabase();
File directory = new File(DBPATH);
if (!directory.exists())
directory.mkdir();
close();
try {
InputStream mInput = new FileInputStream(DB_PATH + DB_NAME);
OutputStream mOutput = new FileOutputStream(DBPATH + DBNAME);
byte[] buffer = new byte[1024];
int length;
while ((length = mInput.read(buffer)) > 0) {
mOutput.write(buffer, 0, length);
}
mOutput.flush();
mOutput.close();
mInput.close();
success = true;
} catch (Exception e) {
Toast.makeText(myContext,
"copyDbToSDCard Error : " + e.getMessage(),
Toast.LENGTH_SHORT).show();
e.fillInStackTrace();
}
return success;
}
You can check is database available or not ?
like this
checkDB()
{
try{
SQLiteDatabase dbe = SQLiteDatabase.openDatabase("selectedFilePath", null,0);
Log.d("opendb","EXIST");
dbe.close();
// DB exits then delete
File file = new File(selectedFilePath);
boolean deleted = file.delete(); <--- this will help you to delete DB
}
catch(Exception e)
{
// DB not exits code to copy database
}
}
the code:
OutputStream mOutput = new FileOutputStream(DBPATH + DBNAME);
and
mOutput.write(buffer, 0, length);
makes that if the file exists it will replace the content of the file with the new data