我有一段从文件中读取数据的代码。我想在此代码中强制 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
}
}
}
最佳答案
免责声明 : 我没有在非Windows平台上测试过这个,所以在不同文件锁定特性的平台上可能会有不同的结果。
如果事先锁定文件,则可以在尝试读取文件时触发 IOException:
java.io.IOException: The process cannot access the file because another process has locked a portion of the file
即使您在同一线程中,这也有效。
这是一些示例代码:
final RandomAccessFile raFile = new RandomAccessFile(csvFile, "rw");
raFile.getChannel().lock();
关于java - 在文件读取期间强制 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2566755/