如何优雅地处理 Java 中的 FileNotFoundException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15315992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:12:36  来源:igfitidea点击:

How to gracefully handle a FileNotFoundexception in java

javaexception

提问by Kai

I'm trying to write a function which returns a file input stream. It looks something like this:

我正在尝试编写一个返回文件输入流的函数。它看起来像这样:

public FileInputStream getFileInputStream() {
    File file;
    try {
        file = new File("somepath");
    } catch (Exception e) {
    }
    FileInputStream fInputStream = new FileInputStream(file);
    return fInputStream;
}

So here is my problem - obviously a file isn't created in the case of an exception. But I NEED a file object to instantiate the FileInputStream. I'm kind of lost here, how can I handle the exception while still returning a valid FileInputStream object?

所以这是我的问题 - 显然在出现异常的情况下不会创建文件。但是我需要一个文件对象来实例化 FileInputStream。我有点迷失在这里,如何在仍然返回有效的 FileInputStream 对象的同时处理异常?

回答by Martijn Courteaux

That is the idea of throwing an exception further. Just throw the exception to the caller.

这就是进一步抛出异常的想法。只需将异常抛出给调用者。

public FileInputStream getFileInputStream() throws FileNotFoundException
{
    File file = new File("somepath");
    FileInputStream fInputStream = new FileInputStream(file);
    return fInputStream;
}

This way, the caller has to handle it. This is the cleanest way of working with it.

这样,调用者必须处理它。这是使用它的最干净的方式。

Remark: You should know that instantiating a Fileobject will never throw an Exception. It is the instantiation of the FileInputStreamthat might throw an Exception.

备注:您应该知道实例化File对象永远不会抛出异常。FileInputStream可能抛出异常的是 的实例化。

回答by Mikhail

Use File.exists(), it check wheater you can do something with a file.

使用File.exists(),它会检查您是否可以对文件执行某些操作。

UPD(Java FileOutputStream Create File if not exists):

UPDJava FileOutputStream 创建文件,如果不存在):

File yourFile = new File("score.txt");
if(!yourFile.exists()) {
    yourFile.createNewFile();
} 
FileOutputStream oFile = new FileOutputStream(yourFile, false); 

回答by Peter Lawrey

Here is the code I use. You might find it interesting.

这是我使用的代码。你可能会觉得很有趣。

public static final Charset UTF_8 = Charset.forName("UTF-8");

/**
 * Provide a normalised path name which can contain SimpleDateFormat syntax.
 * <p/>
 * e.g.  'directory/'yyyyMMdd would produce something like "directory/20130225"
 *
 * @param pathName to use. If it starts or ends with a single quote ' treat as a date format and use the current time
 * @return returns the normalise path.
 */
public static String normalisePath(String pathName) {
    if (pathName.startsWith("'") || pathName.endsWith("'"))
        return new SimpleDateFormat(pathName).format(new Date());
    return pathName;
}

/**
 * Convert a path to a Stream. It looks first in local file system and then the class path.
 * This allows you to override local any file int he class path.
 * <p/>
 * If the name starts with an =, treat the string as the contents.  Useful for unit tests
 * <p/>
 * If the name ends with .gz, treat the stream as compressed.
 * <p/>
 * Formats the name with normalisePath(String).
 *
 * @param name of path
 * @return as an InputStream
 * @throws IOException If the file was not found, or the GZIP Stream was corrupt.
 */
public static InputStream asStream(String name) throws IOException {
    String name2 = normalisePath(name);
    // support in memory files for testing purposes
    if (name2.startsWith("="))
        return new ByteArrayInputStream(name2.getBytes(UTF_8));
    InputStream in;
    try {
        in = new FileInputStream(name2);
    } catch (FileNotFoundException e) {
        in = Reflection.getCallerClass(3).getClassLoader().getResourceAsStream(name2);
        if (in == null)
            throw e;
    }
    if (name2.endsWith(".gz") || name2.endsWith(".GZ"))
        in = new GZIPInputStream(in);
    in = new BufferedInputStream(in);
    return in;
}