Closeable 구현 또는 AutoCloseable 구현
Java를 배우는 중이며 인터페이스 implements Closeable및 implements AutoCloseable인터페이스 에 대한 좋은 설명을 찾을 수 없습니다 .
를 구현할 때 interface CloseableEclipse IDE에서 메소드를 작성했습니다 public void close() throws IOException.
pw.close();인터페이스없이 사용하여 스트림을 닫을 수 있습니다 . 그러나 close()인터페이스를 사용하여 메소드를 구현하는 방법을 이해할 수 없습니다 . 그리고이 인터페이스의 목적은 무엇입니까?
또한 알고 싶습니다 : IOstream실제로 폐쇄 되었는지 어떻게 확인할 수 있습니까?
아래의 기본 코드를 사용하고있었습니다
import java.io.*;
public class IOtest implements AutoCloseable {
public static void main(String[] args) throws IOException {
File file = new File("C:\\test.txt");
PrintWriter pw = new PrintWriter(file);
System.out.println("file has been created");
pw.println("file has been created");
}
@Override
public void close() throws IOException {
}
인터페이스에 익숙하지 않은 것 같습니다. 게시 한 코드에서는을 구현할 필요가 없습니다 AutoCloseable.
만에 (또는한다)를 구현 Closeable또는 AutoCloseable당신에 대해 경우 자신 구현하기 위해 PrintWriter핸들 파일이나 필요가있는 다른 자원이 폐쇄 될 어느.
구현에서는을 호출하면 충분합니다 pw.close(). finally 블록에서이 작업을 수행해야합니다.
PrintWriter pw = null;
try {
File file = new File("C:\\test.txt");
pw = new PrintWriter(file);
} catch (IOException e) {
System.out.println("bad things happen");
} finally {
if (pw != null) {
try {
pw.close();
} catch (IOException e) {
}
}
}
위의 코드는 Java 6과 관련이 있습니다. Java 7에서는보다 우아하게 수행 할 수 있습니다 ( 이 답변 참조 ).
AutoCloseable(Java 7에 도입 됨) 자원 사용 리소스 관용구 를 사용할 수 있습니다 .
public class MyResource implements AutoCloseable {
public void close() throws Exception {
System.out.println("Closing!");
}
}
이제 당신은 말할 수 있습니다 :
try (MyResource res = new MyResource()) {
// use resource here
}
JVM이 close()자동으로 호출 합니다.
Closeable 이전 인터페이스입니다. 몇 가지 이유 To preserve backward compatibility, language designers decided to create a separate one. This allows not only all Closeable classes (like streams throwing IOException) to be used in try-with-resources, but also allows throwing more general checked exceptions from close().
When in doubt, use AutoCloseable, users of your class will be grateful.
Closeable extends AutoCloseable, and is specifically dedicated to IO streams: it throws IOException instead of Exception, and is idempotent, whereas AutoCloseable doesn't provide this guarantee.
This is all explained in the javadoc of both interfaces.
Implementing AutoCloseable (or Closeable) allows a class to be used as a resource of the try-with-resources construct introduced in Java 7, which allows closing such resources automatically at the end of a block, without having to add a finally block which closes the resource explicitely.
Your class doesn't represent a closeable resource, and there's absolutely no point in implementing this interface: an IOTest can't be closed. It shouldn't even be possible to instantiate it, since it doesn't have any instance method. Remember that implementing an interface means that there is a is-a relationship between the class and the interface. You have no such relationship here.
Here is the small example
public class TryWithResource {
public static void main(String[] args) {
try (TestMe r = new TestMe()) {
r.generalTest();
} catch(Exception e) {
System.out.println("From Exception Block");
} finally {
System.out.println("From Final Block");
}
}
}
public class TestMe implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println(" From Close - AutoCloseable ");
}
public void generalTest() {
System.out.println(" GeneralTest ");
}
}
Here is the output:
GeneralTest
From Close - AutoCloseable
From Final Block
The try-with-resources Statement.
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:
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. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:
static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
Please refer to the docs.
Recently I have read a Java SE 8 Programmer Guide ii Book.
I found something about the difference between AutoCloseable vs Closeable.
The AutoCloseable interface was introduced in Java 7. Before that, another interface existed called Closeable. It was similar to what the language designers wanted, with the following exceptions:
Closeablerestricts the type of exception thrown toIOException.Closeablerequires implementations to be idempotent.
The language designers emphasize backward compatibility. Since changing the existing interface was undesirable, they made a new one called AutoCloseable. This new interface is less strict than Closeable. Since Closeable meets the requirements for AutoCloseable, it started implementing AutoCloseable when the latter was introduced.
참고URL : https://stackoverflow.com/questions/13141302/implements-closeable-or-implements-autocloseable
'IT박스' 카테고리의 다른 글
| 이미 존재하고 어쨌든 보호 된 리눅스에서 파일을 비우는 방법 (“잘라 내기”)은 무엇입니까? (0) | 2020.07.28 |
|---|---|
| 처음 세 열을 제외하고 모두 인쇄 (0) | 2020.07.28 |
| 반응 형 웹 디자인은 데스크톱에서는 작동하지만 모바일 장치에서는 작동하지 않습니다 (0) | 2020.07.28 |
| 반응-DOM이 렌더링되는 동안 로딩 화면이 표시됩니까? (0) | 2020.07.28 |
| 날짜 문자열을 날짜로 구문 분석하는 방법은 무엇입니까? (0) | 2020.07.27 |