I have to read a text and I created a method
public void load(String fname){
try{
BufferedReader reader = new BufferedReader(new FileReader(fname));
String id_cliente = reader.readLine();
while(id_cliente!=null){
String name_surname = reader.readLine();
int num_titoli = Integer.parseInt(reader.readLine());
String[] sb = name_surname.split(" ");
Cliente cl = new Cliente(id_cliente,sb[0],sb[1]);
clientilist.put(Integer.parseInt(id_cliente.substring(1)),cl);
for(int i = 0; i < num_titoli; i++){
cl.addTitolo(String titolo = reader.readLine());
}
id_cliente = reader.readLine();
}
}
catch(FileNotFoundException fnfe){
try{
}
catch(FileNotFoundExeption fnfe){
System.exit(0);
}
}
catch(IOException ioe){
}
}
what I would do is to check if the fname file exists.if it’s not a FileNotFoundExceptionwill be thrown.Inside it I have to try to open another file.if it is not present so exit with an error message.how can i do?
In the catch block of the first try catch statement you could put any code you want and it will be executed when the exception occurs. You could read another file, try reading the same file again, ask user to point to the correct file, …
But as mentioned a better solution is to check if the file exists before you create the reader. And if that fails you can fallback on another file (what if that one fails also?)
In the next code I adapted your method to have a check and throw an exception if file isn’t valid. On using that method you can react on that. Note that you haven’t opened any readers if you gave 2 invalid filenames.
And this is how your load function would look like: