我必须阅读文本并创建一个方法
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){
}
}
我要做的是检查fname
文件是否存在。如果不存在,将抛出FileNotFoundException
。在其中我必须尝试打开另一个文件。如果它不存在,则退出并显示错误消息。我该怎么办?
最佳答案
在第一个 try catch 语句的 catch block 中,您可以放置任何您想要的代码,当异常发生时它将被执行。您可以读取另一个文件,尝试再次读取同一文件,要求用户指向正确的文件,...
但正如前面提到的,更好的解决方案是在创建阅读器之前检查文件是否存在。如果失败,您可以退回到另一个文件(如果那个文件也失败怎么办?)
在下一个代码中,我调整了您的方法以进行检查并在文件无效时抛出异常。使用该方法时,您可以对此使用react。请注意,如果您提供了 2 个无效的文件名,则您还没有打开任何阅读器。
try{
load(fname);
}catch(Exception e){
try{
load(alternativeFName);
}catch(Exception e){
System.out.println("None of the files are available");
e.printStackTrace();
}
}
这就是你的加载函数的样子:
public void load(String fname) throws Exception {
// try opening file
File file = new File(fname);
// check if valid file
if( !file.exists() ){
// if no valid file throw exception so we can react on that
throw new Exception("File not available: "+fname);
}
//your code for reading here, at this point you know the file exists
//...
}
关于java - 抛出下一个异常返回阅读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8505133/