[Path to Java Development] (20) try-with-resource exception Declaration
Try-with-resources is a new exception handling mechanism in Java 7, which can easily close the resources used in the try-catch Block.
Before Java 7, the resources used in the program need to be explicitly disabled, and the process is a bit cumbersome, as shown below:
package com.qunar.lectures.tryResource;
-
import java.io.*;
import java.util.ArrayList;
import java.util.List;
-
/**
* Created by xiaosi on 16-3-4.
*/
public class TryResourceDemo {
// Obtain resource data
public static List readLines(String resourcePath) {
String path = TryResourceDemo.class.getResource(resourcePath).getPath();
File file = new File(path);
-
if (!file.exists()) {
throw new RuntimeException("Can not find file + " + resourcePath);
}//if
-
if (!file.isFile()) {
throw new RuntimeException(resourcePath + " is not a regular file");
}//if
-
FileInputStream fis;
InputStreamReader isr;
BufferedReader br = null;
try {
fis = new FileInputStream(file);
isr = new InputStreamReader(fis, "UTF-8");
br = new BufferedReader(isr);
List lines = new ArrayList ();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}//while
return lines;
}
catch (IOException e) {
throw new RuntimeException("Read file failed , file=" + resourcePath, e);
}
finally {
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}//if
}//finally
}
public static void main(String[] args) {
List lines = readLines("/a.txt");
for(String line : lines){
System.out.println("line:" + line);
}//for
}
}
Assume that the try statement block throws an exception and the finally statement block is executed. It is also assumed that the finally statement block throws an exception. Which exception will be propagated out of the Call Stack? Even if the exception thrown in the try statement block is more relevant to the Exception Propagation, the exception finally thrown in the finally statement block will be propagated outward Based on the call stack.
private static void printFileJava7() throws IOException {
try(FileInputStream input = new FileInputStream("file.txt")) {
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
}
}
We can see the first line:
try(FileInputStream input = new FileInputStream("file.txt")) {
This is the usage of the try-with-resource structure. The FileInputStream type variable is declared and assigned a value in parentheses after the try keyword. The declared variables can be directly used in the following code, that is, in the same scope. When the try statement block stops running, FileInputStream is automatically disabled. This is because FileInputStream implements the java. lang. AutoCloseable interface in java. All classes that implement this interface can be used in the try-with-resources structure.
When an exception is thrown in the try-with-resources structure and the FileInputStreami is closed (the close method is called), an exception is thrown, the exceptions thrown in the try-with-resources structure will be propagated out, and the exceptions thrown when the FileInputStreami is disabled are blocked. This is opposite to the example of using the old style code at the beginning of the article (Closing the resource in the finally statement block.
In JDK 7, you can use try-with-resource to handle exceptions and disable resources as long as you implement classes or interfaces of the AutoCloseable or Closeable interfaces.
You can use multiple resources in the block and these resources can be automatically disabled:
package com.qunar.lectures.tryResource;
-
import java.io.*;
import java.util.ArrayList;
import java.util.List;
-
/**
* Created by xiaosi on 16-3-4.
*/
public class TryResourceDemo {
// Obtain resource data
public static List readLines(String resourcePath) {
String path = TryResourceDemo.class.getResource(resourcePath).getPath();
File file = new File(path);
-
if (!file.exists()) {
throw new RuntimeException("Can not find file + " + resourcePath);
}//if
-
if (!file.isFile()) {
throw new RuntimeException(resourcePath + " is not a regular file");
}//if
// Use the try-with-resource Method to automatically release resources
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr)){
List lines = new ArrayList ();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}//while
return lines;
}
catch (IOException e) {
throw new RuntimeException("Read file failed , file=" + resourcePath, e);
}
}
public static void main(String[] args) {
List lines = readLines("/a.txt");
for(String line : lines){
System.out.println("line:" + line);
}//for
}
}