Java 7 try-with-resources를 올바르게 사용하고 있습니까?
버퍼링 된 판독기와 파일 판독기가 닫히고 예외가 발생하면 리소스가 해제 될 것으로 예상합니다.
public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException
{
try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
{
return read(br);
}
}
그러나 catch
성공적인 폐쇄를위한 조항 이 있어야 합니까?
편집하다:
본질적으로 Java 7의 위 코드는 Java 6의 아래 코드와 같습니다.
public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException
{
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(filePath));
return read(br);
}
catch (Exception ex)
{
throw ex;
}
finally
{
try
{
if (br != null) br.close();
}
catch(Exception ex)
{
}
}
return null;
}
정확하고 catch
절에 대한 요구 사항이 없습니다 . Oracle Java 7 doc은 예외가 실제로 발생했는지 여부에 관계없이 리소스가 닫힐 것이라고 말합니다 .
catch
예외에 대응하려는 경우에만 절을 사용해야합니다 . catch
조항이 실행됩니다 후 리소스가 닫힙니다.
다음은 Oracle 자습서의 일부입니다 .
다음 예제는 파일에서 첫 번째 줄을 읽습니다. BufferedReader 인스턴스를 사용하여 파일에서 데이터를 읽습니다. BufferedReader는 프로그램이 완료된 후 닫아야하는 리소스입니다.
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
} // In this example, the resource declared in the try-with-resources statement is a BufferedReader.
... BufferedReader 인스턴스는 try-with-resource 문에서 선언되기 때문에 try 문이 정상적으로 완료되는지 갑작스럽게 완료되는지에 관계없이 닫힙니다 (IOException을 던지는 BufferedReader.readLine 메서드의 결과로).
편집하다
새로 수정 된 질문에 관하여 :
Java 6의 코드 catch
는 finally
블록을 실행 하고 그 이후에 실행합니다 . 이로 인해 리소스가 catch
블록 에서 여전히 잠재적으로 열릴 수 있습니다 .
In Java 7 syntax, resources are closed before the catch
block, so resources are already closed during the catch
block execution. This is documented in the above link:
In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
Your usage of try-with-resources will work fine in this particular case, but it is not quite correct in general. You should not chain resources like that because it may lead to unpleasant surprises. Assume you have a variable buffer size:
public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException
{
int sz = /* get buffer size somehow */
try (BufferedReader br = new BufferedReader(new FileReader(filePath), sz))
{
return read(br);
}
}
Assume something went wrong and you ended up with sz
being negative. In this case your file resource (created via new FileReader(filePath)
) will NOT be closed.
To avoid this problem you should specify each resource separately like this:
public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException
{
int sz = /* get buffer size somehow */
try (FileReader file = new FileReader(filePath);
BufferedReader br = new BufferedReader(file, sz))
{
return read(br);
}
}
In this case even if initialization of br
fails file
still gets closed. You can find more details here and here.
참고URL : https://stackoverflow.com/questions/17650970/am-i-using-the-java-7-try-with-resources-correctly
'program story' 카테고리의 다른 글
구성 요소 외부에있는 클릭 이벤트를 수신하는 방법 (0) | 2020.09.16 |
---|---|
C #을 사용하여 Windows Form에 파일 찾아보기 단추를 추가하는 방법 (0) | 2020.09.16 |
MongoDB에서 '좋지 않음'연산자를 어떻게 사용할 수 있습니까? (0) | 2020.09.16 |
Ruby는 기능적인 언어입니까? (0) | 2020.09.16 |
if 절을 종료하는 방법 (0) | 2020.09.16 |