【问题标题】:How to gracefully handle a FileNotFoundexception in java [duplicate]如何在java中优雅地处理FileNotFoundexception [重复]
【发布时间】:2013-02-25 07:06:07
【问题描述】:

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

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

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

【问题讨论】:

  • 所有受到异常行为影响的东西都应该包装在try...catch 块中。这样可以缓解您的问题。
  • new File("somepath") 永远不会抛出异常(尽管理论上它可能会抛出错误)。你为什么trying它?
  • @cheeken 是对的 - 创建文件可能产生的唯一异常是 NullPointerException,并且可以通过使用静态字符串作为构造函数来缓解。

标签: java exception


【解决方案1】:

这就是进一步抛出异常的想法。只需向调用者抛出异常即可。

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

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

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

【讨论】:

  • 我会throws FileNotFoundException,因为没有必要扩大类型。
  • 我刚刚学到了一些东西。非常感谢!
【解决方案2】:

使用File.exists(),它会检查你是否可以对文件做一些事情。

UPD(Java FileOutputStream Create File if not exists):

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

【讨论】:

【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多