【问题标题】:Trying to output a string variable to a .txt file within an IF statement. - Java尝试在 IF 语句中将字符串变量输出到 .txt 文件。 - 爪哇
【发布时间】:2013-05-05 23:14:13
【问题描述】:

我对 java 还是很陌生,我还有很多东西要学。我正在尝试将变量中的数据输出到文本文件,但我不确定为什么这不起作用。谁能帮帮我?

if ("Y".equals(output_to_file)) {
        System.out.print("You selected Yes");
        PrintStream out = null;
        try {
            out = new PrintStream(new FileOutputStream("filename.txt"));
            out.print(first_input);
        }
        finally {
            if (out != null) out.close();
        }
    }
    else System.out.print("You selected No");

"(new FileOutputStream("filename.txt"))" 带有红色下划线,表示:未处理的异常:java.io.FileNotFoundException

感谢您的帮助!

【问题讨论】:

    标签: java if-statement output


    【解决方案1】:

    任何时候你在进行文件操作,都有可能抛出FileNotFoundException。因此,Java 希望您告诉它在抛出异常时该怎么做。因此,您需要为可能的FileNotFoundException 添加一个catch 子句。您已经有一个 try 块,因此您只需在 finally 子句之前添加一个 catch 子句:

            try {
            out = new PrintStream(new FileOutputStream("filename.txt"));
            out.print(first_input);
            }
            catch(FileNotFoundException e) {
            //do something in the event that a FNFE is thrown
            }
            finally {
            if (out != null) out.close();
        }
    }
    

    【讨论】:

    • 完美运行。非常感谢!
    • 很高兴能帮上忙 :) 由于您是新来的,请注意 - 如果我的回答(或其他任何人的回答)对您有所帮助,请随时点击旁边的复选标记接受它。这样做会给你+2声望点,并增加人们在未来帮助你的可能性:)
    • 谢谢,我会在两分钟内勾选。 :D
    猜你喜欢
    • 2017-03-08
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    相关资源
    最近更新 更多