ファイルからデータを読み取るコードがあります。テスト目的で、このコードで IOException を強制したい (この場合、コードが正しいカスタム例外をスローするかどうかを確認したい)。
たとえば、読み取りから保護されたファイルを作成する方法はありますか? いくつかのセキュリティチェックに対処することが役立つでしょうか?
FileNotFoundException には別の catch 句があるため、存在しないファイルの名前を渡すことは役に立たないことに注意してください。
質問をよりよく理解するためのコードは次のとおりです。
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(csvFile));
String rawLine;
while ((rawLine = reader.readLine()) != null) {
// some work is done here
}
} catch (FileNotFoundException e) {
throw new SomeCustomException();
} catch (IOException e) {
throw new SomeCustomException();
} finally {
// close the input stream
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// ignore
}
}
}