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.
Related
I want to create a sub directory which is non-private under the Environment.DIRECTORY_PICTURES directory. I used the code shown below but of no avail. The directory is created but it remains private. I don't know where I'm wrong.
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyImages");
file.mkdirs();
File f = new File(file,"Image1");
First, you have not created a file, at least in the code that is shown above. You have created a Java File object, and you created a directory, but you did not create a file for Image1, and so your directory is empty. I know of no way to force your empty directory to be picked up by anything, though you should see it if you use adb shell or DDMS to examine your device.
When you do eventually write a file to this directory, be sure to call getFD().sync() on the FileOutputStream before you close() that stream. Then, use MediaScannerConnection and its static scanFile() method to have your newly-created file be indexed by the MediaStore. Until you do this, your newly-created file will not be visible via MTP or many third-party apps.
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.
This is my code to create a File Object. I am sure that the file is existing. However the file length() returns 0 and the exists() returns false too.
File uploadFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/DSC00050.jpg");
int totalSize = (int) uploadFile.length(); // Get size of file, bytes
After Writing File uploadFile = new File(...); it will not create the file itself.
AFAIK If File.exists() is returning false, then file just doesn't exist yet.
but yes You can create file by calling file.createNewFile()
if exists() returns false means the file does not exist or not accessible. Make sure that the SD card is mounted and that your app has sufficient permission i.e. READ_EXTERNAL_STORAGE. I suspect this is the problem because you should get exception in that case.
The other thing is to log the absolute file path uploadFile.getAbsolutePath() and make sure that it is correct.
Edit:
Are you sure that your image is directly under the DCIM folder not DCIM/Camera ? Use any file browser in Android and check the file complete path. I do not see any other problems in the code.
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);
I want to save a file on internal storage into a specific folder. My code is:
File mediaDir = new File("media");
if (!mediaDir.exists()){
mediaDir.createNewFile();
mediaDir.mkdir();
}
File f = new File(getLocalPath());
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(data);
fos.close();
getLocalPath returns /data/data/myPackage/files/media/qmhUZU.jpg but when I want to create the media folder I'm getting the exception "java.io.IOException: Read-only file system". Any ideas how to write my files on internal phone storage in in folder media? Thanks.
You should use ContextWrapper like this:
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);
As always, refer to documentation, ContextWrapper has a lot to offer.
You should create the media dir appended to what getLocalPath() returns.
I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/ or /mnt/sdcard/. Let me explain.
If you execute the following statement:
File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();
It will resolve the path to the root /data/ somewhere higher up in Android.
I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/ without me translating anything on my own.
File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();
A quick fix would be to change your following code:
File f = new File(getLocalPath().replace("/data/data/", "/"));
Hope this helps
Write a file
When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:
getFilesDir()
Returns a File representing an internal directory for your app.
getCacheDir()
Returns a File representing an internal directory for your
app's temporary cache files.
Be sure to delete each file once it is no longer needed and implement a reasonable
size limit for the amount of memory you use at any given time, such as 1MB.
Caution: If the system runs low on storage, it may delete your cache files without warning.
Hi try this it will create directory + file inside it
File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
mediaDir.mkdir();
}
File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();
System.out.println("Your file has been written");