java - How to handle a FileNotFoundException? -
i'm tinkering around on small application read numbers in file. runs far, have encountered problem don't know how can fix it. if user enters, unintentionally maybe, wrong filename filenotfoundexception thrown jvm, catch in invoking method. want give him (the user) 2 tries enter correct filename, don't know how can invoke method again opening file when i'm in catch-block below. illustrate transient solution below, i'm not sure if effective/elegant way solve problem:
//code omitted int temp = 0; while(true) { filename = input.next(); try { ex.fileopen(filename); } catch(filenotfoundexception e) { if(temp++ == 3) { system.err.println("you have entered filename 3 times consecutively wrongly"); return; } continue; } break; } //do other stuff
input scanner reads user input , assigns string-variable filename. fileopen method takes filename, opens file, reads content , write numbers in vector.
so, appreciate every support more experienced java programmers.
greetings tom
you use this,
public class appmain { public static void main(string[] args) throws ioexception { string filepath = input.next(); inputstream = getinputstream(filepath); int temp = 0; while(is == null && temp < 3){ filepath = input.next(); = getinputstream(filepath); temp++; } if(is == null){ system.err.println("you have entered filename 3 times consecutively wrongly"); return; } ......... ......... } private static inputstream getinputstream(string filepath){ inputstream = null; try{ = new fileinputstream(filepath); return is; }catch (ioexception ioexception) { return null; } } }
Comments
Post a Comment