My program checks if a specific file exists in the default cache folder. If the file exists, it opens it and reads the contents. If the file does not exist, the file gets pulled from the web and is stored in the cache folder. The problem I'm having is that, no matter if the file is in the cache folder or not, my file test always returns false. The funny thing is that, even though the file test returns false, I can still open the file from the cache folder and read it. I can pull a list of files in the cache folder and I can see the file is there, but when I do the file test to see if the file is there, it returns false, even though I know the file is there and I can open it and see it's contents.
I tried the regular exists() test and even reading each file in the cache directory one by one and comparing the name to the file I'm looking for and still returns false.
Thanks for any help in advance!
String file = "test.txt"
String content = "testing";
putFile(file, content);
Boolean fileIsThere = checkFile(file);
public Boolean checkFile(String file){
Boolean fileExists = false;
// regular file test - always returns false, even if the file is there
File f = new File(file);
if (f.exists())
fileExists = true;
// comparing each individual file in the directory - also returns false
String[] dirFiles = fileList();
for (int i = 0; i < dirFiles.length; i++) {
if (dirFiles[i] == file){
fileExists = true;
break;
}
}
return fileExists;
}
public void putFile(String file, String content){
try {
FileOutputStream fos = openFileOutput(file, Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
Log.w("putFile", "Error (" + e.toString() + ") with: " + file);
}
}
Any ideas? I'm thinking that since I'm putting the files in the cache folder, I will always get false on the file test. I just want to see if anyone else came across this and has a fix for it, or if I have to make a specific directory and store my files there, or something else. Could "Context.MODE_PRIVATE" in putFile() have anything to do with it?
If you want to test existention of file stored in your Context storage data/data/nameOfPackage/files/text.txt you have to rewrite String file like this
String file = "/data/data/nameOfPackage/files/test.txt"
Then you can check exists() method of your test.txt file. I hope it will help you. :)
if (f.exists() && f.length() > 0) fileExists = true;
This works for me!
Related
I am making an application in which I have to save video files internally(in app memory when app is uninstalled all the filed should also be uninstalled).For this I have read many articles and googled a lot and found different solutions and after that I made a method there I wrote the code for that here is the code
public static boolean checkIfAlreadyDownloaded(Context context, String rhymeName) {
ContextWrapper cw = new ContextWrapper(context);
File rhymeDirectory = cw.getDir(Constants.INTERNAL_DIRECTORY_NAME, Context.MODE_PRIVATE);
if (rhymeDirectory.exists()) {
File individualRhyme = new File(rhymeDirectory, rhymeName);
if (individualRhyme.exists())
return true;
}
return false;
}
Here Constants.INTERNAL_DIRECTORY NAME is "Rhymes"
what I understand is if there is no directory then it returns false but When I install my app first time it return true.Even I uninstalled it and then reinstall it is always returning true .My question is "why it is always returning true"? Shouldn't it return false first time?Correct me please if I am wrong.
ContextWrapper.getDir() creates the directory if necessary, as said in the documentation:
public File getDir (String name, int mode)
Retrieve, creating if needed, a new directory in which the application can place its own custom data files.
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 to write into the file
For deleting a file from internal :
if (new File("path/to/file").delete()) {
// Deleted
} else {
// Not deleted
}
I wish delete music file stored on my phone (has no SD card) in Music folder. I have file path and File.exists() said true. Next, File.delete() also said true, but file stay in its place. But! After "deletion" I can no longer play this file, edit name and also can't copy it. But I can delete it manually.
I've set android.permission.WRITE_EXTERNAL_STORAGE. OS 4.4.4 GPE
Where is my mistake? Any suggestions, thanks.
File file = new File(Path);
if (file.exists()){
file.setWritable(true, false);
return file.delete();
}
Windows is not looking at external storage directly. It is looking at the data served up by the Media Transfer Protocol (MTP) server on your Android device. It, in turn, is working with the MediaStore index, not the actual filesystem.
If you make any change to external storage, such as deleting a file, you need to update MediaStore. Off the cuff, I do not recall exactly how to do that for a deleted file, though I would consider trying to use MediaScannerConnection and scanFile() to perhaps scan the directory that contained the deleted file.
So, my final solution that seems to work is:
public Boolean deleteTrack(String key){
MusicTrack track = getAlbum(0).getTrackByKey(key);
if (track == null) return false;
File file = new File(track.getData().Path);
if (file.exists()){
file.setWritable(true, false);
String where = MediaStore.Audio.Media.DATA +"=\""+ track.getData().Path +"\"";
if (context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, where, null) == 1){
if (file.exists()){
Boolean d = file.delete();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
return d;
}
return true;
}
}
return false;
}
Both files are present on the sdcard, but for whatever reason exists() returns false the the png file.
//String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png";
String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-1200240592.pdf";
File file2 = new File(path);
if (null != file2)
{
if(file2.exists())
{
LOG.x("file exist");
}
else
{
LOG.x("file does not exist");
}
}
Now, I've look at what's under the hood, what the method file.exists() does actually and this is what it does:
public boolean exists()
{
return doAccess(F_OK);
}
private boolean doAccess(int mode)
{
try
{
return Libcore.os.access(path, mode);
}
catch (ErrnoException errnoException)
{
return false;
}
}
May it be that the method finishes by throwing the exception and returning false?
If so,
how can I make this work
what other options to check if a file exists on the sdcard are available for use?
Thanks.
1 You need get the permission of device
Add this to AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2 Get the external storage directory
File sdDir = Environment.getExternalStorageDirectory();
3 At last, check the file
File file = new File(sdDir + filename /* what you want to load in SD card */);
if (!file.canRead()) {
return false;
}
return true;
Note: filename is the path in the sdcard, not in root.
For example: you want find
/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
then filename is
./Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
.
Please try this code. Hope it should helpful for you. I am using this code only. Its working fine for me to find the file is exists or not. Please try and let me know.
File file = new File(path);
if (!file.isFile()) {
Log.e("uploadFile", "Source File not exist :" + filePath);
}else{
Log.e("uploadFile","file exist");
}
Check that USB Storage is not connected to the PC. Since Android device is connected to the PC as storage the files are not available for the application and you get FALSE to File.Exists().
Check file exist in internal storage
Example : /storage/emulated/0/FOLDER_NAME/FILE_NAME.EXTENTION
check permission (write storage)
and check file exist or not
public static boolean isFilePresent(String fileName) {
return getFilePath(fileName).isFile();
}
get File from the file name
public static File getFilePath(String fileName){
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "FOLDER_NAME");
File filePath = new File(folder + "/" + fileName);
return filePath;
}
I want to know whether it is possible to write data in /etc folder (or any other folder besides data)? If yes, how to do that?
And if not possible, any way to store a permanent data? For scenario example, an app is uninstalled (or clear data), but a specific file will still remain.
thank you.
i'm not sure about /etc folder, but the stuff saved in /data folder is managed by android automatically itself. So when you uninstall an app, anything related to it is also removed from data folder.
However, to store a file permanently besides Data folder on your SdCard, see the code below:
public static boolean saveOnFile(String msg){
boolean saved = false;
String filename = "yourFileName.extension";
try{
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File root = new File(Environment.getExternalStorageDirectory(), "/YourFolderOnSdCard/");
//create root folders if they do not exist
if(!root.exists()){
root.mkdirs();
}
//now lets save file in our directory structure
File file = new File(root, filename);
FileWriter fw = new FileWriter(file);
fw.append(msg);
fw.flush();
fw.close();
saved = true;
}
else
Log.e("Save", "Mounted media is not available or is write-protected");
}
catch (Exception e) { Log.e("Save", e.toString()); }
return saved;
}
This Data Storage guide could be useful.
I'm facing a problem in the following code. What I'm trying to do is delete a folder and all of it's contents. Sometimes it works and sometimes it doesn't.
boolean success = false;
String directory = Environment.getExternalStorageDirectory().toString();
directory += "/.SID/Downloads/DC0601";
File path = new File(directory);
File[] files;
try
{
files = path.listFiles();
if (files == null)
{
success = path.delete();
}
else
{
for (int i = 0; i < files.length; i ++)
{
File currentFile = files[i];
if (currentFile != null)
currentFile.delete();
}
success = path.delete();
}
}
catch (Exception e)
{
success = false;
Log.e("deleteData Exception: ", e.toString());
}
What's happening here is that in some cases, the directory 'DC0601' does exist and does contain files on the sdcard, but when this code runs, success is returned as false because 'files' is null. Why is it null?!!
I simply can't understand it. If I completely shut down the app and then run it, it can detect the files and the directory and can successfully delete them. Otherwise if I've been using the app for a while and then run the code, it thinks that directory and those files aren't there.
Has anyone faced similar issues with delete()?
I see you're grabbing the external storage directory, but I don't see you checking it's state.
What does Environment.getExternalStorageState() return?
Should you be using
Environment.getExternalStorageDirectory().getPath()
I've never actually used .toString().