Force IOException during file reading

DixonD picture DixonD · Apr 2, 2010 · Viewed 33k times · Source

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?

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
            }
        }
    }

Answer

Weston B picture Weston B · Jul 25, 2011

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.

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.

Here's some sample code:

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