在读取文件期间强制IOException

在读取文件期间强制IOException

本文介绍了在读取文件期间强制IOException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码可以从文件中读取数据.我想在此代码中强制IOException进行测试(我想检查这种情况下代码是否抛出正确的自定义异常).

I have a piece of code that reads data from a file. I want to force IOException in this code for testing purposes (I want to check if the code throws a correct custom exception in this case).

例如,有什么方法可以创建一个防止被读取的文件吗?也许处理一些安全检查会有所帮助?

Is there any way to create a file which is protected from being read, for example? Maybe dealing with some security checks can help?

请注意,传递不存在的文件的名称无济于事,因为FileNotFoundException具有单独的catch子句.

Please, note that passing the name of a non-existent file cannot help, because FileNotFoundException has a separate catch clause.

下面是一段代码,可以更好地理解这个问题:

Here is the piece of code for better understanding of the question:

    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平台上对此进行过测试,因此可能有所不同在具有不同文件锁定特性的平台上获得结果.

Disclaimer: I have not tested this on a non-Windows platform, so it may have different results on a platform with different file locking characteristics.

如果您事先锁定了文件,则在尝试读取文件时可以触发IOException:

If you lock the file beforehand, you can trigger an IOException when something attempts to read from it:

java.io.IOException: The process cannot access the file because another process has locked a portion of the file

即使您处于同一线程中,此方法也可以使用.

This works even if you are in the same thread.

以下是一些示例代码:

final RandomAccessFile raFile = new RandomAccessFile(csvFile, "rw");
raFile.getChannel().lock();

这篇关于在读取文件期间强制IOException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:43