'尝试捕获'重建从java 1.7到java 1.6

chr*_*ina 1 java try-catch

我正在使用其他人的jar文件,但我需要将源代码添加到我的项目中,并在导入这些包时编译它们.问题是这个jar文件好像是生成的java1.7所以它使用了一些文件java1.7.但我正在使用java1.6.对于此源代码:

public Properties getDefaults() {
    try (InputStream stream
            = getClass().getResourceAsStream(PROPERTY_FILE)) {

        Properties properties = new Properties();
        properties.load(stream);
        return properties;

    } catch (IOException e) {
        throw new RuntimeException(e);

    }
}
Run Code Online (Sandbox Code Playgroud)

日食提供了这样的错误提示:

Resource specification not allowed here for source level below 1.7
Run Code Online (Sandbox Code Playgroud)

那我怎么能重写这样的代码,以便它可以处理java1.6

rge*_*man 5

要重新编写与Java 1.6兼容的try-with-resource语句,请执行以下操作:

  • try块开始之前声明变量.
  • try块的顶部创建变量.
  • 添加一个finally将关闭资源的块.

例:

InputStream stream = null;
try
{
    stream = getClass().getResourceAsStream(PROPERTY_FILE));
    // Rest of try block is the same
}
// catch block is the same
finally
{
    if (stream != null)
    {
        try {
            stream.close();
        } catch (IOException ignored) { }
    }
}
Run Code Online (Sandbox Code Playgroud)