开发者

Test if file exists

I'm trying to open a file in android like this :

  try
   {
      FileInputStream fIn = context.openFileInput(FILE);
      DataInputStream in = new DataInputStream(fIn);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      if(in!=null)
          in.close();
   }
   catch(Exception e)
   {  }开发者_如何转开发

, but in case the file does not exists a file not found exception is thrown . I'd like to know how could I test if the file exists before attempting to open it.


I think the best way to know if a file exists, without actually trying to open it, is as follows:

File file = getContext().getFileStreamPath(FILE_NAME);
if(file.exists()) ...


The documentation says Context.openFileInput either returns an inputStream (file found) or throws a FileNotFoundException (not found)

http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)

So it looks like the exception is your "test".

You could also try using standard

java.io.File file = new java.io.File(PATHTOYOURCONTEXT , FILE);
if (file.exists()) {
    FileInputStream fIn = new FileInputStream(file);
}

But that is not recommended. Context.openFileInput() and Context.openFileOutput() make sure you stay in your applications storage context on the device, and that all of your files get deleted when your app gets uninstalled.


With the standard java.io.File this is the function I have created, and works correctly:

private static final String APP_SD_PATH = "/Android/data/com.pkg.myPackage";
...
public boolean fileExistsInSD(String sFileName){
    String sFolder = Environment.getExternalStorageDirectory().toString() + 
            APP_SD_PATH + "/Myfolder";
    String sFile=sFolder+"/"+sFileName;
    java.io.File file = new java.io.File(sFile);
    return file.exists();
}


why dont you just catch the FileNotFound exception and take that as the file not being present.


If you want to ensure a file exists (i.e. if it doesn't exist create a new one, if it does then don't erase it) then use File.createNewFile:

https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()

e.g.

{
        String pathName = <file path name>
        File file = new File (pathName);
        Uri pathURI = Uri.fromFile (file);
        boolean created;

        String mIOException = "";
        String mSecException = "";

        try
        {
            created = file.createNewFile();

            if (created)
            {
                ctxt.sendBroadcast (new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pathURI));
            }
        }
        catch (IOException ioex)
        {
            mIOException = ioex.getMessage();
        }
        catch (SecurityException sex)
        {
            mSecException = sex.getMessage();
        }

}


If you want to open a file in any case (i.e. if it doesn't exist create a new one, if it does append to the old one) you can use this, no testing necessary:

public static void write_custom_log(String message){
        File root = Environment.getExternalStorageDirectory();
        try{
            BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/mnt/sdcard/tjb_tests/tjb_log_file.txt"),true));

            if (root.canWrite()){
                fw.write(message);
                fw.close();
                }
            } catch (IOException e) {
                Log.e("One", "Could not write file " + e.getMessage());
            }
    }


My suggestion is to check length of the file. if file.length() returns 0 that means file doesn't exist.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜