Android RenameTo leaves empty file - android

Could you please help me. renameTo() leaves empty old file. So I see 2 files in file system with new name and old name. The size of old file is 0. If I delete old file after renaming it says that file does not exist while staying in file system.
An absolute path of directory is:
/storage/sdcard0/DCIM/Camera
My code:
String dir = oldpath.substring(0, oldpath.lastIndexOf("/"));
File directory = new File(dir);
File from = new File(directory, oldfilename);
File to = new File(directory, newname);
renamed = from.renameTo(to);

Try this code:
File sdcard = new File("/storage/sdcard0/DCIM/Camera");
File from = new File(sdcard, "from.txt"); // Don't forget to set the file extension.
File to = new File(sdcard, "to.txt"); // In this case, we have a '.txt' file extension.
from.renameTo(to);
You can get the sdcard directory in String type programmatically by using this code:
String sdcard = Environment.getExternalStorageDirectory().getPath();
Don't forget to add this permission in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

RenameTo leaves an empty copy of the original file if the file is opened by another process.
For example, I wanted to rename a file after the DownloadManager finished downloading it. The DownloadManager apparently notifies the BroadcastReceivers after the download, but before closing the file. This caused the renameTo in the onReceive to leave an empty copy. To solve this problem, I had to make the BroadcastReceiver to wait half a second before renaming the file.

You must remember about two things : The file and the file extension (file type). The following is wrong way sometimes, in case of deleting and renaming file :
File file = new File (dir+"/"+myfile)
The right way is :
File file = new File (dir, myfile+".db");
For the Full Aprroach, you could look at Answer Here.

Related

I can't write to the external SD card(extSdCard) in Android Studio

I have created an android app that needs to create a folder and write text files on my external SD card(extSdCard). I am using the Galaxy S4 device and have written the following codes for that. I already know the path of /mnt/.. file and have created a string for it. The android manifest.xml file uses the permission.i have checked the codes in "adb logcat" in Cmd prompt and it does not give any error but doesn't create any folder. The device has also been checked unconnected with the PC. Would appreciate if you help me. Here is the code.
String externalFilePath="/mnt/extSdCard/tmp";
Log.d(TAG, "externalFilePath is: "+externalFilePath);
File myfile = new File(externalFilePath, "Hello");
First of all make sure that you have this line inside your manifest,xml, somewhere outside application tag.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Then you can write a File doing this :
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(sdcard.getAbsolutePath() + "/tmp/");
// creates if doesn't exists
dir.mkdir();
// create a File
File file = new File(dir, "Example.txt");
FileOutputStream os = outStream = new FileOutputStream(file);
//this is the text that will be inside of the Example.txt
String data = "Hello world";
os.write(data.getBytes());
os.close();
Hope it helps :)
try this code to generate files under your application package
File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
// Replace DIRECTORY_PICTURES with your needs
File file = new File(path, "Hello");
Also make sure you have added the permissions

What's the root of my android app?

I'm trying to develop a simple android app. I want to know if an image exist in one of my apps' folder, but I don't know what's the root of my app. I tried...
File nomeFile = new File("res/drawable-hdpi/imagename.jpg")
File nomeFile = new File("myappanem/res/drawable-hdpi/imagename.jpg")
...but it doesn't work.
Try This :
File YourFile = new File(Environment.getExternalStorageDirectory(), "/Android/data/....yourfile.txt");
No you cant access drawable or manifest after packaging. because there will be no "drawable" folder or manifest file at all. All your drawables packed in APK file after installation. You cant reach them.
But you can access any folder of your phone in your app like that.
Firstly make directory.
File directory = new File(Environment.getExternalStorageDirectory()+File.separator
+"Your folder");
directory.mkdirs();
Access your folder like that.
String fileUrl = "/Your folder/a.png";
String file = android.os.Environment.getExternalStorageDirectory().getPath() +
fileUrl;
File f = new File(file);
whether your taking about internal memory of your application cache directory
//use this for internal memory
String path =Environment.getDataDirectory().getAbsolutePath();
File myImage=new File(path,"your file name.extension");
//use this for cache directory
String path=getApplicationContext().getDir("" , Context.MODE_PRIVATE);
File myImage=new File(path,"your file name.extension")

Rename a file in the internal storage

What's the best/easiest way to rename a file in the application's internal storage? I find it a bit strange that there is a Context.deleteFile() method, but no "move" or "rename" function. Do I have to go all the way through saving the file's contents, deleting it, creating a new one and then copying the contents into that one? Or is there a way to copy a file over an existing file?
Update (Aug. 30, 2012):
As per the suggested solution below, which I cannot get to work:
I have a file called shoppinglists.csv
Then I create a new file called shoppinglists.tmp, and copy the contents from shoppinglists.csv AND some new entries into that. The shoppinglist.tmp file is then a new version of the shoppinglists.csv file
Then I delete the old shoppinglists.csv file
Then I need to rename the shoppinglists.tmp file to shoppinglists.csv
I tried this:
ctx.deleteFile("shoppinglists.csv"); <--- delete the old file
File oldfile = new File("shoppinglists.tmp");
File newfile = new File("shoppinglists.csv");
oldfile.renameTo(newfile);
However, this doesn't work. After deleteFile(), nothing more happens, and I'm left with the new shoppinglists.tmp file.
What am I missing?
NB: There are no errors or anything in LogCat.
Instead of using a raw File constructor, use the method getFileStreamPath provided by the Context. That is to say, do:
File oldfile = ctx.getFileStreamPath("shoppinglists.tmp");
File newfile = ctx.getFileStreamPath("shoppinglists.csv");
oldfile.renameTo(newfile);
renameTO() doesn't work in my environment (Eclipse Indigo, AVD with android version 2.3). The solution is to skip the temporary file method alltogeher, since it doesn't seem to be possible to solve in any reasonable time frame.
I think we cannot use File.renameTo() method in Internal Storage environment.
Renaming a file in this environment, can do:
- Copy content of the old file to new file.
- Delete old file.
File file = new File("your old file/folder name");
File file2 = new File("your new file/folder name");
boolean success = file.renameTo(file2);

Can't read the file from internal storage (file doesn't exist issue)

I have a routed device and when I do this
adb shell cat /data/misc/bluetooth/dynamic_auto_pairing.conf
it prints the content of this file.
But in my code when I write something like this, it says that the file does not exist. Well from the console I see it I know is there, but from code I can't read it. My question is what is the problem , am I missing some permission or what is the problem ? can someone provide me with some code to read the content from this file.
Thanks
File pa = new File("/data/misc/bluetooth/","dynamic_auto_pairing.conf");
//this doesn't works also
//File pa = new File("/data/misc/bluetooth","dynamic_auto_pairing.conf");
//File pa = new File("/data/misc/bluetooth/dynamic_auto_pairing.conf");
if(pa.exists()){
Log.v("tag", "does exists");
}else{
Log.v("tag", "does NOT exist");
}
If the file is on sdcard, try:
File pa = new File(Environment.getExternalStorageDirectory() + "/data/misc/bluetooth/dynamic_auto_pairing.conf");
Also try to add:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
outside <application></application> in your manifest file.
EDIT
If the file is in internal memory: Your app can read only from a special folder in internal memory. The path to that folder is returned by:
getFilesDir().getAbsolutePath()
So put the file there and read it with openFileInput().
More info:
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
From the docs for File...
public File (String dirPath, String name)
Constructs a new File using the specified directory path and file name, placing a path separator between the two.
In your code you are using...
File pa = new File("/data/misc/bluetooth/","dynamic_auto_pairing.conf");
...and because your dirPath ends with a separator "/data/misc/bluetooth/" it will result in two separators. In other words, effective path will be...
/data/misc/bluetooth//dynamic_auto_pairing.conf
Note the // after 'bluetooth`
If you are using android 6.0 or higher. You must request permission in code.

Writing hidden file .nomedia fails on internal storage

I want to create .nomedia file in the internal cache directory where I will store images and tried the following..
File dir = getCacheDir();
File output = new File(dir, ".nomedia");
boolean fileCreated = output.createNewFile();
When I try this fileCreated is false and the file doesn't get created.
If I used nomedia without a dot the file gets created but this is no use as the MediaScanner is looking if the .nomedia file exists.
I also tried this with a FileOutputStream and to write data in the file in case it was because I was only created an empty file but this doesn't work either.
Anyone have an idea why this could be failing?
Hmm, are you really sure that the file not already exists? Please note that you need to do an ls -a to see a file starting with a dot.
The documentation of File.createNewFile() says:
Returns true if the file has been
created, false if it already exists.
If the file is not created for other reasons (i.e. security), it should throw an exception.

Categories

Resources