1

I am using a jar file from other person, but I need to add the source codes into my project and compile them when I import such packages. The issue is this jar file seems to generated by java1.7 so it uses some java1.7 fetures. But I am using java1.6. For this source codes:

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

    }
}

The eclipse gives such error hints:

Resource specification not allowed here for source level below 1.7

Then how could I rewrite such codes so that it can be handled by java1.6?

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
chrisTina
  • 2,298
  • 9
  • 40
  • 74

1 Answers1

5

To re-write a try-with-resource statement compatible with Java 1.6, do the following:

  • Declare the variable before the try block begins.
  • Create the variable at the top of the try block.
  • Add a finally block that will close the resource.

Example:

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) { }
    }
}
rgettman
  • 176,041
  • 30
  • 275
  • 357