My code works with jre7 and not jre6. Is there a possibility to make it compatible with jre6:
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
} catch(IOException e) {
}
Eclipse prompts an error stating:
The resource type BufferedReader does not implement java.lang.AutoCloseable
Could you explain the problem here? What is the solution? Thanks
Replace the new try
construct with the classic finally
clause:
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
} catch(IOException e) {
} finally {
br.close();
}
This will close the reader in any case, also if an exception has been thrown from the inside try block. Only AutoCloseable classes can be used in try-with-resources construct, and java 6 BufferedReader
is not (java 7 BufferedReader
is).
You as using the try-with-resources statement. All objects implementing java.lang.AutoCloseable can be used as a resource. BufferedReader is not extending from AutoCloseble in Java 6. That's why you are seeing this error.
There is a good tutorial explaining the difference here .
the below code uses try
with resource of type AutoClosable
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
} catch(IOException e) {
}
which is the feature added in Java7, so it works well in Java7.
but same will not work in Java 6 or below.
Java 6 or below support simple try without autoclose type resource.
so your code should be like below in java 6
BufferedReader br = new BufferedReader(new FileReader(fileName));
try{
//do whatever you want
} catch(IOException e) {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.