开发者

File exists test does not work on cache folder...?

开发者 https://www.devze.com 2023-01-27 07:45 出处:网络
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 st

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 fil开发者_C百科e 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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号