Trying to output a string variable to a .txt file within an IF statement. - Java -


i'm pretty new java , still have alot learn. i'm trying output data within variable text file, , i'm not sure why not work. me out?

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);         }         {             if (out != null) out.close();         }     }     else system.out.print("you selected no"); 

"(new fileoutputstream("filename.txt"))" underlined red, , says: unhandled exception: java.io.filenotfoundexception

thanks help!

anytime you're doing file operations, there possiblity filenotfoundexception thrown. therefore, java wants tell in event 1 thrown. thus, need add catch clause possible filenotfoundexception. have try block, need add catch clause before finally clause:

        try {         out = new printstream(new fileoutputstream("filename.txt"));         out.print(first_input);         }         catch(filenotfoundexception e) {         //do in event fnfe thrown         }         {         if (out != null) out.close();     } } 

Comments