Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 测试文件是否存在_Java_Android_File - Fatal编程技术网

Java 测试文件是否存在

Java 测试文件是否存在,java,android,file,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

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

,但如果文件不存在,将引发“未找到文件”异常。我想知道在尝试打开文件之前如何测试文件是否存在

文档中说Context.openFileInput要么返回inputStream(已找到文件),要么抛出FileNotFoundException(未找到)

所以看起来例外是你的“测试”

您也可以尝试使用标准

java.io.File file = new java.io.File(PATHTOYOURCONTEXT , FILE);
if (file.exists()) {
    FileInputStream fIn = new FileInputStream(file);
}
但这并不可取。Context.openFileInput()和Context.openFileOutput()确保您保持在设备上的应用程序存储上下文中,并且所有文件
卸载应用程序时删除。

为什么不捕获FileNotFound异常,并将其视为文件不存在。

我认为在不实际打开文件的情况下,了解文件是否存在的最佳方法如下:

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

希望有帮助,再见

如果您想在任何情况下打开一个文件(即,如果该文件不存在,请创建一个新文件,如果它确实附加到旧文件中),您可以使用此选项,无需进行任何测试:

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

我的建议是检查文件的长度
如果file.length()返回0,则表示文件不存在。

使用标准的
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();
}

如果要确保某个文件存在(即,如果该文件不存在,请创建一个新文件,如果存在,请不要将其删除),然后使用file.createNewFile:

e、 g

{
字符串路径名=
文件文件=新文件(路径名);
Uri pathURI=Uri.fromFile(文件);
布尔创建;
字符串“=”;
字符串mSecException=“”;
尝试
{
created=file.createNewFile();
如果(已创建)
{
ctxt.sendBroadcast(新意图(Intent.ACTION\u MEDIA\u SCANNER\u SCAN\u FILE,pathURI));
}
}
捕获(IOException ioex)
{
mIOException=ioex.getMessage();
}
捕获(安全例外性)
{
mSecException=sex.getMessage();
}
}

如果这是您实际的异常处理程序,请重新考虑它@Thomas,它曾经是我的一个子句的异常处理程序,就像这个一样(从“网络”上复制了一些代码)。我想复制的一个好规则是在实际使用它之前检查所有内容。我在使用自己的代码时遇到了足够多的麻烦。可能的重复(我知道这个Q比较老,但另一个Q通常有更多的投票权,并且更适合当前的Android),这就是我实际使用的方式,但我想知道是否还有另一个way@rantravee:您要做的是捕获所有异常。除了有点草率之外,它也没有告诉你为什么会发生异常。如果您只捕获了
FileNotFoundException
,您将在捕获时知道它是因为文件不存在而被抛出的(而不是泛型异常,它可能意味着try块中的某个调用或它调用的东西或它调用的东西出错,或者……)通常情况下,最好是例外就是例外。检查文件是否存在,以及在创建文件后,文件是否仍然不存在,请保留try/catch作为备用。检查sd卡上是否存在目标文件非常有效-谢谢!工作,我假设它比仅仅为了查看文件是否存在而获取InputStream更有效。很好。如果文件名=文件名+路径呢?你是什么意思?文件名应该是相对于应用程序的(未知)私有目录的文件路径。文件名包含子目录这一事实对于测试其存在性来说不是问题;如果您必须创建该文件,您可以像在Java中一样确保所需的子目录,@lencinhaus如何:file file=new file(filePath);如果(file.exists()),因为我已经有了一个URI文件路径,不需要额外的步骤来提取文件名?与您的方式相比,这是否确实打开了文件?如果您尝试访问您外部的文件,例如非根设备上的“/system/bin/file”,则此操作不起作用。可能存在长度为0Context的文件。getExternalFilesDir()返回的路径与Environment.getExternalStorageDirectory()相同。toString()+APP_SD_PATH
{
        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();
        }

}