有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

异常如何在java中优雅地处理FileNotFoundexception

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

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

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


共 (3) 个答案

  1. # 1 楼答案

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

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

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

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

  2. # 2 楼答案

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

    UPDJava FileOutputStream Create File if not exists):

    File yourFile = new File("score.txt");
    if(!yourFile.exists()) {
        yourFile.createNewFile();
    } 
    FileOutputStream oFile = new FileOutputStream(yourFile, false); 
    
  3. # 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;
    }