问题描述
下面的代码片段抛出错误 1. 当输入文件路径无效时 - FILENOTFOUNDEXCEPTION 2. 当输出文件在 excel 中打开时 - FILENOTFOUNDEXCEPTION 说所述文件在另一个进程中打开
我想建议用户检查输入文件路径或关闭打开的 excel(或在记事本中打开)。 我如何分别捕捉这些?
try(FileReader fr = new FileReader("D:/Test.log");
BufferedReader br = new BufferedReader(fr);) {
doSomething(br);
//writing to CSV
String[] arr = {"aaa","bbb"};
FileWriter outputfile= new
FileWriter("D:/output.csv",false);
CSVWriter writer = new CSVWriter(outputfile);
writer.writeNext(arr);
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
1楼
您应该将代码分成两个 try/cath 语句
BufferedReader br;
try {
FileReader fr = new FileReader("D:/Test.log");
br = new BufferedReader(fr);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error("Input file not found");
} catch (IOException e) {
e.printStackTrace();
}
doSomething(br);
//writing to CSV
String[] arr = {"aaa","bbb"};
try {
FileWriteroutputfile = new FileWriter("D:/output.csv",false);
CSVWriter writer = new CSVWriter(outputfile);
writer.writeNext(arr);
writer.close();
} catch (IOException e) {
e.printStackTrace();
log.error("Output file already in use");
}