4

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

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

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

4

3 回答 3

12

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

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

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

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

于 2013-03-09T21:15:25.793 回答
3

使用File.exists(),它会检查你可以对文件做些什么。

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

File yourFile = new File("score.txt");
if(!yourFile.exists()) {
    yourFile.createNewFile();
} 
FileOutputStream oFile = new FileOutputStream(yourFile, false); 
于 2013-03-09T21:16:53.637 回答
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;
}
于 2013-03-09T21:50:26.563 回答