2010-05-07 74 views
46

我想在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) 
    { } 

,但如果该文件不存在,未发现异常被抛出的文件。我想知道如何在试图打开文件之前测试该文件是否存在。

+2

如果这是您的实际异常处理程序,请重新考虑它。 http://www.rockstarprogrammer.org/post/2007/jun/15/empty-catch-blocks-are-always-wrong/ – Thomas 2010-05-07 08:16:49

+0

@Thomas曾经是我的异常处理程序的一个子句就像这个(复制一些代码关闭'网络。)我想一个好的复制规则就是在实际使用它之前检查一切。我有足够的麻烦使用我的OWN代码。 – 2012-08-29 21:13:36

回答

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); 
} 

但不推荐。 Context.openFileInput()和Context.openFileOutput()确保您保持在设备上的应用程序存储上下文中,并且在卸载应用程序时删除所有文件 。

+0

适用于检查SD卡上是否存在目标文件 - 谢谢! – mishkin 2010-11-20 04:28:45

+0

非常感谢:) – 2011-08-26 05:01:22

+0

为什么不推荐? – 2011-11-29 14:13:30

2

你为什么不抓住FileNotFound异常,并将其作为文件不存在。

+0

这就是我实际做的方式,但我想知道是否有另一种方式 – rantravee 2010-05-07 09:39:57

+0

@rantravee:您所采取的方式是捕捉所有异常。除了sl,之外,它也不会告诉你为什么会发生异常。如果你只捕获了'FileNotFoundException',那么当你捕获它时,你会知道它被抛出,因为文件不存在(而不是泛型异常,这可能意味着在你的try块或者某些东西的某个地方出现了错误它调用或调用它的东西,或....) – cHao 2011-05-28 15:08:45

+0

通常情况下,如果异常是最好的 - 例外。检查文件是否存在,如果创建后它仍然不存在,请将try/catch作为后退。 – SK9 2011-09-30 02:12:22

160

我想知道的最好的方式,如果一个文件存在,实际上并没有试图打开它,如下:

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

希望帮助,再见!

+0

工程,我假设它比获取InputStream来查看文件是否存在更有效。尼斯。 – 2012-03-01 12:08:04

+5

如果FILE_NAME =文件名+路径怎么办? – 2012-07-27 23:18:04

+0

你是什么意思? FILE_NAME应该是相对于应用程序的(未知)专用目录的文件路径。 FILE_NAME包含子目录的事实对于测试它的存在不是问题;如果您必须创建该文件,则可以像往常一样在Java中确保所需的子目录[请参阅文档](http://developer.android.com/reference/java/io/File.html#mkdirs()) – lencinhaus 2012-10-16 18:18:16

0

如果你想在任何情况下打开一个文件(即,如果它不存在,创建一个新的,如果它不追加到旧),你可以利用这一点,没有必要的检测:

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()); 
      } 
    } 
-2

我的建议是检查文件的长度。 if file.length() returns 0这意味着文件不存在。

+9

可能有一个长度为0的文件 – AaA 2012-08-30 08:57:21

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(); 
} 
+0

Context.getExternalFilesDir()返回与Environment.getExternalStorageDirectory()。toString()+ APP_SD_PATH – riper 2013-04-03 17:19:05

1

(即,如果它不存在,创建一个新的,如果它不那么就不要删除它),然后使用File.createNewFile:

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

{ 
     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(); 
     } 

}