如何在java中优雅地处理FileNotFoundexception

时间:2013-03-09 21:13:48

标签: java exception

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

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

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

3 个答案:

答案 0 :(得分:10)

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

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

这样,调用者必须处理它。这是使用它的最简洁方法。

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

答案 1 :(得分:4)

使用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); 

答案 2 :(得分:0)

这是我使用的代码。你可能会发现它很有趣。

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