preface

Today, a baby asked me why my code is exactly the same as yours, but when I run it, I get an error. When I look at the code, I say, “You’re stepping on a hole, you’re not writing close() for your file operation.” She said, you also did not write duck, how you do not report a mistake. I say this is because I’m using a new syntax introduced in Java7, try-with-recources, which helps me automatically call the close() method after the file operation.

Not try – with – resourses

After normal file operations, the close() statement is called to close the stream and flush the cache to actually write the contents of the cache to disk (the buffer is to avoid frequent disk operations, which can be time-consuming). It is written as follows:

        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(DiskConstant.DISK_FILE, "rw");
            randomAccessFile.seek(diskBlockIndex * DiskConstant.BLOCK_SIZE + boffset);
            randomAccessFile.write(bytes, offset, length);
        } finally {
            if(randomAccessFile ! =null) { randomAccessFile.close(); }}Copy the code

However, this approach is extremely tedious and contains a lot of template code, with the core code just three lines inside the try{}. And it’s easy to forget that calling close() in finally causes an error.

The try – with – resources capitalization

Classes with new try() in parentheses will automatically call Closeable’s close() method after the end of the try(){} block, as long as the class implements Closeable. Therefore, in all non-special cases, file operations should use the try-with-resources syntax to simplify the code and avoid missing the close() method. The following code is equivalent to the non-try-with-resources method above, with five fewer lines of code.

        try (RandomAccessFile randomAccessFile = new RandomAccessFile(DiskConstant.DISK_FILE, "rw")) {
            randomAccessFile.seek(diskBlockIndex * DiskConstant.BLOCK_SIZE + boffset);
            randomAccessFile.write(bytes, offset, length);
        }
Copy the code