尝试关闭文本编写器时出错

时间:2014-09-30 20:13:04

标签: java file-io

这是我第一次尝试文件编写以保存java程序中的数据,我在SO上找到了这个解决方案,但是当我尝试关闭PrintWriter时,我的finally语句中出现错误,说&#34 ;出来无法解决"。 非常感谢。

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();
        }       

    }

}

1 个答案:

答案 0 :(得分: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() {
    ...
}