How can i restore my database to its original directory? - android

Here is the code to save/copy my data in to SDcard,when i click on Backup Button my database saved in sdcard in NOTEIT directory and now i want to restore this database when i click on restore button into my default directory so can anyone tell me how to achieve this?
public static void backupDatabase() throws IOException
{
try
{
File dbFile = new File(Environment.getDataDirectory() + "/data/com.neelrazin.noteit/databases/data");
File exportDir = new File(Environment.getExternalStorageDirectory()+"/NOTEIT");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
file.createNewFile();
FileChannel inChannel = new FileInputStream(dbFile).getChannel(); //fails here
FileChannel outChannel = new FileOutputStream(file).getChannel();
try
{
inChannel.transferTo(0, inChannel.size(), outChannel);
}
finally
{
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

I believe the restore is an exact opposite of your backup.
Like this:
public static void restoreDatabase() throws IOException
{
try
{
File dbFile = new File(Environment.getDataDirectory() + "/data/com.neelrazin.noteit/databases/data");
File importDir = new File(Environment.getExternalStorageDirectory()+"/NOTEIT");
if (!importDir.exists())
{
throw new IOException("External 'NOTEIT' directory does not exist.");
return;
}
File file = new File(importDir, dbFile.getName());
if (!file.exists()) 
{
    throw new IOException("Does not exist external db file: NOTEIT/" + dbFile.getName());
    return;
}
FileChannel outChannel = new FileOutputStream(dbFile).getChannel();
FileChannel inChannel = new FileInputStream(file).getChannel();
try
{
inChannel.transferTo(0, inChannel.size(), outChannel);
}
finally
{
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

Related

Writting to root sdcard folder

I am trying to copy a file over to the root SD card on an Android device.
When I execute the code, it is going to the sdcard/Android/Data/<packageName>/files folder.
I have tried several different options without any success.
Also, I have checked the app to make sure it has write and read access to external memory.
private void copyfiles() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("ini");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null)
for (String filename: files) {
InputStream in = null;
OutputStream out = null;
try { in = assetManager.open("sdcard/" + filename);
//File outFile = new File(Environment.getExternalStorageDirectory(), filename);
File outFile = new File(getExternalFilesDir(null), filename);
if (!(outFile.exists())) { // File does not exist...
out = new FileOutputStream(outFile);
pastefiles( in , out);
}
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
} finally {
if ( in != null) {
try { in .close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}

How to Copy the Internal Default ringtones to External Memory in Android

Please help me out I am not getting the default ringtone file path.
Can any body tell how to get access to the default ringtone in Android. Here is my code for doing that thing. I have commented the path that I gave directly to asset manager to open the file and read it.
public void copyAssets() {
AssetManager assetManager = this.getAssets();
// String FileName="//media/internal/audio/media/";
File io=getFilesDir();
String[] files = null;
try {
files = assetManager.list("");
// files=assetManager.list(FileName);
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
// File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
// File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
// FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual
//
try {
in = assetManager.open("Ringtone");
// File myFolder = new File(Environment.getDataDirectory() + "/myFolder");
File myFolder = this.getDir("myFolder", this.MODE_PRIVATE);
File fileWithinMyDir=new File(myFolder,"Ringtoness");
out = new FileOutputStream(fileWithinMyDir);
copyFile(in, out);
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
}
public 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);
}
}`

java.io.FileNotFoundException: /: open failed: EISDIR (Is a directory)

File albumF = getVideoAlbumDir();
String path = albumF.getAbsolutePath();
// path =/storage/emulated/0/Pictures/.MyImages (Hidden folder)
// fileSelected.fileName()=IMG_20140417_113847.jpg
File localFile = new File(path + "/" + fileSelected.fileName());
Log.v("", "file exist===" + localFile.exists());
if (!localFile.exists()) {
Log.v("", "inside if===");
Log.v("", "Parent Filet===" + localFile.getParentFile());
localFile.getParentFile().mkdirs();
// localFile.createNewFile();
copy(fileSelected, localFile);
} else {
Log.v("", "inside else===");
mCurrentPhotoPath = localFile.getAbsolutePath();
uploadMediaFile();
}
This copy method copies data from dropbox file to my local storage.
private void copy(final Entry fileSelected, final File localFile) {
final ProgressDialog pd = ProgressDialog.show(ChatActivity.this,
"Downloading...", "Please wait...");
new Thread(new Runnable() {
#Override
public void run() {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
DropboxInputStream fd;
try {
fd = mDBApi.getFileStream(fileSelected.path,
localFile.getAbsolutePath());
br = new BufferedInputStream(fd);
bw = new BufferedOutputStream(new FileOutputStream(
localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
pd.dismiss();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
android.os.Message msg = new android.os.Message();
msg.arg1 = 100;
if (msg.arg1 >= 100) {
progressHandler.sendMessage(msg);
mCurrentPhotoPath = localFile.getAbsolutePath();
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
I am creating file in a folder using localFile.getParentFile().mkdirs();
I got above error when I upload this file to server.
how to fix this?
If you've tried all other options - and problem still persists - then maybe you have a case when the file you want to create matches name of already existing directory.(which might be earlier created my some call to mkdirs() maybe accidentally).
Example:
You want to save file Test\test.pdf but you already have folder Test\Test.pdf\

file.delete() from android internal storage return false

I have a method to download a image from url and save it in a folder at Internal storage
public void saveDynamicImage(String url,String fileName, String folderName) {
InputStream iStream;
BufferedInputStream buffInputStream;
ByteArrayBuffer byteArray = null;
try {
HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
iStream = httpResponse.getEntity().getContent();
buffInputStream = new BufferedInputStream(iStream, 8 * 1024);
byteArray = new ByteArrayBuffer(50);
int current = 0;
while ((current = buffInputStream.read()) != -1) {
byteArray.append((byte) current);
}
} catch (ClientProtocolException e1) {
} catch (IOException e1) {
}
File dynamicImageDir = context.getDir(AppConstants.DYNAMIC_IMAGE, Context.MODE_PRIVATE);
File appNamefileDir = new File(dynamicImageDir, BaseActivity.appDataStore.getAppName());
appNamefileDir.mkdirs();
File controlNameDir = new File(appNamefileDir, folderName);
controlNameDir.mkdirs();
File file = new File(controlNameDir, fileName);
try {
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(byteArray.toByteArray());
outputStream.close();
System.out.println("DynamicImage saving over!..");
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
i want to delete the whole directory at a point of time. My method to delete entire directory is
public void deleteDynamicImage() throws NullPointerException,FileNotFoundException {
File rootDirectory = context.getDir(AppConstants.DYNAMIC_IMAGE, Context.MODE_WORLD_WRITEABLE);
boolean status = rootDirectory.delete();
Log.e("", "delete : "+status);
}
i am getting the status as 'false'. files are created and working fine. only problem in deletion. Is there any thing I am missing?
Is your file a directory?
If it's, you need to delete file in this folder first
this code is work well
public void deleteDirectory(File file) {
if( file.exists() ) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
file.delete();
}
}
To delete Directory use this:
public void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) for (File child : fileOrDirectory.listFiles())
DeleteRecursive(child);
fileOrDirectory.delete();
}
How to delete File in Android:
public void deleteFile(String filePath){
if(filePath.startsWith("content://")){
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(Uri.parse(filePath), null, null);
}else {
File file = new File(filePath);
if(file.exists()) {
if (file.delete()) {
Log.e(TAG, "File deleted.");
}else {
Log.e(TAG, "Failed to delete file!");
}
}else {
Log.e(TAG, "File not exist!");
}
}
}
Important Note:
if you get file path from Uri [Don't use Uri.toString()] as it will return file path in file:/// format, in this case [new File(filePath)] will not work. So to get file path always use Uri.getPath().
You are trying to delete a directory. File.delete() works on directory only if this is empty

have ones app copy file from webpage

I have made an app that have to copy a file from a webpage, the following code doesn't do the job, it can't find the file
File ekstern = new File("http://192.168.13.40/cache.manifest");
copyFile(ekstern, intern);
and the copyFile method:
public static void copyFile(File in, File out) throws IOException {
FileChannel inChannel = new
FileInputStream(in).getChannel();
FileChannel outChannel = new
FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(),
outChannel);
}
catch (IOException e) {
throw e;
}
finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
But the code says that the file doesn't exists
testing with ekstern.exists()
You can't use File object to get something from a webpage. You have to use an HttpClient

Categories

Resources