In this particular case, your use of try-with-resources will work fine, but overall this is not entirely correct. You should not bind such resources, because it can lead to unpleasant surprises. Suppose you have a buffer variable size:
public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException { int sz = try (BufferedReader br = new BufferedReader(new FileReader(filePath), sz)) { return read(br); } }
Suppose something went wrong and you ended up with sz negative. In this case, your file resource (created using new FileReader(filePath) ) will be closed by NOT .
To avoid this problem, you must specify each resource separately as follows:
public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException { int sz = try (FileReader file = new FileReader(filePath); BufferedReader br = new BufferedReader(file, sz)) { return read(br); } }
In this case, even if br initialization failed file , it still closes. You can find more information here and here .
Andrii Polunin Jan 25 '14 at 9:37 2014-01-25 09:37
source share