简体   繁体   中英

Handling exceptions with RandomAccessFile and FileChannel.write

(I am new to java and am getting my bearings right, so please bear with the basic nature of my questions.)

I am looking at some open source code which has a function like this:

private void writeFile(File jDir) throws Exception {
    File fn = new File(jDir, "abcdef.txt");

    FileChannel fc = new RandomAccessFile(fn, "rw").getChannel(); // R.A.F. leak here

    ByteBuffer zeros = ByteBuffer.allocate(512);
    fc.write(zeros, 4*1024*1024);
    fc.position(0);

    for (int i = 1; i <= 10; i++) {
        fc.write(ByteBuffer.wrap("JunkJunkJunk".getBytes()));
    }
}

Now when I load the project in eclipse, there is a leak warning. The following fixes that warning:

private void writeFile(File jDir) throws Exception {
    File fn = new File(jDir, "abcdef.txt");

    RandomAccessFile raf = new RandomAccessFile(fn, "rw"); // get the raf created
    FileChannel fc = raf.getChannel();

    ByteBuffer zeros = ByteBuffer.allocate(512);
    fc.write(zeros, 4*1024*1024);
    fc.position(0);

    for (int i = 1; i <= 10; i++) {
        fc.write(ByteBuffer.wrap("ABCDEFGHIJKL".getBytes()));
    }

    fc.close();
    raf.close();
}

But I think the above is also not complete and I need to enclose the relevant code in try-catch blocks and release raf and fc in the finally block. Is my understanding correct ? Many implementations and examples found online do not do this, so I am not sure what the right thing to do is here.

Is my understanding correct

It is.

Check also try-with-resource if you use java 7 (and lombok @Cleanup that can be handy)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM