我有一段代码从文件中读取数据.我想在此代码中强制执行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
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 11
免责声明:我没有在非Windows平台上测试过,因此在具有不同文件锁定特性的平台上可能会有不同的结果.
如果事先锁定了文件,则可以在尝试从中读取某些内容时触发IOException:
java.io.IOException: The process cannot access the file because another process has locked a portion of the file
Run Code Online (Sandbox Code Playgroud)
即使您在同一个线程中,这也有效.
这是一些示例代码:
final RandomAccessFile raFile = new RandomAccessFile(csvFile, "rw");
raFile.getChannel().lock();
Run Code Online (Sandbox Code Playgroud)
Ada*_*kin -2
你总是可以抛出你自己的IOException:
throw new IOException("Test IOException");
Run Code Online (Sandbox Code Playgroud)