2013-05-05 50 views
0

我对Java很新,我还有很多东西要学。我试图将一个变量中的数据输出到一个文本文件,我不知道为什么这不起作用。任何人都可以帮我吗?试图将输出字符串变量输出到IF语句中的.txt文件。 - 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"); 

“(新FileOutputStream中(” FILENAME.TXT “))” 的红色下划线,并说:未处理的异常:java.io.FileNotFoundException

感谢您的帮助!

回答

2

无论何时您正在进行文件操作,都有可能导致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(); 
    } 
} 
+0

完美。非常感谢! – 2013-05-05 23:24:10

+0

很高兴我可以帮助:)因为你是新来的人,所以请提醒一下 - 如果我的回答(或其他人)帮助你,可以点击旁边的复选标记来接受它。这样做会给你+2的声望点,并增加人们在未来可以帮助你的可能性:) – drewmoore 2013-05-05 23:25:17

+0

谢谢,在它允许我将两分钟内打勾。 :d – 2013-05-05 23:27:36