2014-09-30 82 views
0

这是我第一次尝试在文件写入过程中将数据保存到一个java程序中,并且我在这里找到了这个解决方案,但是当我试图在最终语句中出现错误时关闭PrintWriter,说出“无法解决”。 非常感谢。尝试关闭文本编写器时出错

import java.io.FileNotFoundException; 
    import java.io.PrintWriter; 


public class MedConcept { 

    public static void main(String[] args) { 
     ConsoleReader console = new ConsoleReader(System.in); 
     try { 
      PrintWriter out = new PrintWriter("med.txt"); 
      System.out.println("Name of the medication:"); 
      String medName = console.readLine(); 

      System.out.println("The Dosage of the medication:"); 
      Double medDose = console.readDouble(); 

      System.out.println("Time of day to take"); 
      String dayTime = console.readLine(); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     }finally{ 
      out.close(); 
     }  

    } 

} 
+3

您正在try-block内部进行定义,它不在finally块的范围内。在try块之前定义出来。如有必要,用'null'初始化它。 – 2014-09-30 20:13:48

+0

当我在try-block外面的时候,catch语句给了我一个错误,告诉我:“FileNotFoundException的无法到达的catch块,这个异常永远不会从try语句体中抛出”@KuluLimpa – sirnomnomz 2014-09-30 20:15:07

回答

4

可变outtry块,其不处于finally块可见内部声明。将声明移到外面,并在关闭时检查它是否为空。

PrintWriter out = null; 
    try { 
     out = new PrintWriter("med.txt"); 
     System.out.println("Name of the medication:"); 
     String medName = console.readLine(); 

     System.out.println("The Dosage of the medication:"); 
     Double medDose = console.readDouble(); 

     System.out.println("Time of day to take"); 
     String dayTime = console.readLine(); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    }finally{ 
     if(out != null) { 
      out.close(); 
     } 
    } 

如果您使用的是Java 7,您可以避免与try-with-resources语句手动关闭PrintWriter

try (PrintWriter out = new PrintWriter("med.txt")) { 
    ... 
} catch() { 
    ... 
} 
+1

+1提到try-与资源 – 2014-09-30 20:16:25