簡體   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