测试文件是否存在

ran*_*vee 47 java android file

我试图在android中打开一个文件,如下所示:

  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)
   {  }
Run Code Online (Sandbox Code Playgroud)

,但是如果文件不存在,则抛出未找到文件的异常.我想知道如何在尝试打开文件之前测试文件是否存在.

len*_*aus 161

我认为最好的方法是知道文件是否存在,而不是实际尝试打开它,如下所示:

File file = getContext().getFileStreamPath(FILE_NAME);
if(file.exists()) ...
Run Code Online (Sandbox Code Playgroud)

希望有所帮助,再见!

  • 如果FILE_NAME =文件名+路径怎么办? (5认同)

rom*_*oll 26

文档说Context.openFileInput返回一个inputStream(找到的文件)或抛出一个FileNotFoundException(未找到)

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

所以看起来例外是你的"测试".

您也可以尝试使用标准

java.io.File file = new java.io.File(PATHTOYOURCONTEXT , FILE);
if (file.exists()) {
    FileInputStream fIn = new FileInputStream(file);
}
Run Code Online (Sandbox Code Playgroud)

但不建议这样做.Context.openFileInput()和Context.openFileOutput()确保您保留在设备上的应用程序存储上下文中,并在卸载应用程序时删除所有文件.


小智 5

使用标准,java.io.File这是我创建的功能,并且正常工作:

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();
}
Run Code Online (Sandbox Code Playgroud)