java PrintWriter无法解析

我不知道为什么我在第11行的日食中得到“无法解决”的消息

import java.io.*; public class driver { public static void main(String[] args) { try { PrintWriter out = new PrintWriter("output.txt"); } catch (FileNotFoundException e) { System.out.print("file not found"); e.printStackTrace(); } out.print("hello"); out.close(); } } 

好的,现在我有了这个

 import java.io.*; public class driver { public static void main(String[] args) { PrintWriter out = null; try { out = new PrintWriter("output.txt"); } catch (FileNotFoundException e) { System.out.print("file not found"); e.printStackTrace(); } out.print("hello"); out.close(); } } 

为什么在我关闭后eclipse不创建文件?

您还可以使用JDK 1.7中引入的新的try-with-resource块,这样做的好处是您无需担心关闭任何实现Closable Interface的资源。

那么代码将如下所示:

 try (PrintWriter out = new PrintWriter("output.txt")) { out.print("hello"); } catch (FileNotFoundException e) { System.out.print("file not found"); e.printStackTrace(); } 

try块之前声明您的PrintWriter ,因此它的范围不限于try块。