繁体   English   中英

使用RandomAccessFile和FileChannel.write处理异常

[英]Handling exceptions with RandomAccessFile and FileChannel.write

(我是Java的新手,并且对我的方向很了解,所以请忍受我的问题的基本性质。)

我正在看一些具有如下功能的开源代码:

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()));
    }
}

现在,当我将项目加载到eclipse中时,会出现泄漏警告。 以下修复了该警告:

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();
}

但是,我觉得上面也是不完整的,我需要在封闭的try-catch块的相关代码,并释放raffcfinally阻塞。 我的理解正确吗? 在网上找到的许多实现和示例都不能做到这一点,所以我不确定在这里做什么是正确的。

我的理解正确吗

它是。

检查还尝试-与资源,如果你使用的Java 7(和龙目岛 @Cleanup ,可以很方便)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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