在我看来,您对接口不是很熟悉。在您发布的代码中,您无需实现
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有关。在Java7中,可以更优雅地完成此操作(请参阅下答案])。



