2012-05-14 82 views
25

以下代码是我如何确定文件是否存在于内部存储器MODE_PRIVATE中。试图检查内部存储器中是否存在文件

public boolean isset(String filename){ 
    FileInputStream fos = null; 
    try { 
     fos = openFileInput(filename); 
     //fos = openFileInput(getFilesDir()+"/"+filename); 
     if (fos != null) { 
     return true; 
     }else{ 
     return false; 
     } 
    } catch (FileNotFoundException e) { 
     return false; 
    } 

    //File file=new File(mContext.getFilesDir(),filename); 

    //boolean exists = fos.exists(); 
    } 

但是,它进入例外状态,不会继续执行代码。它没有做回报。为什么?

+1

你能为我们提供的堆栈跟踪? – Nicholas

回答

101

希望这种方法可以帮助你。

public boolean fileExist(String fname){ 
    File file = getBaseContext().getFileStreamPath(fname); 
    return file.exists(); 
} 
+3

正确的答案,Michael Petrotta你应该接受这个 – Amanni

+1

@bsara为什么基本上下文而不是应用程序的上下文,或者两者兼而有之? –

+0

getApplicationContext()也可以工作 –

4

对于内部存储,这对我的作品:

public boolean isFilePresent(String fileName) { 
    String path = getContext().getFilesDir().getAbsolutePath() + "/" + fileName; 
    File file = new File(path); 
    return file.exists(); 
} 
相关问题