JAVA FileChannel會關閉文件流

File file = new File(filePath);
        BufferedOutputStream stream = null;
        FileOutputStream fstream = null;
        FileChannel fileChannel = null;
        FileLock fileLock = null;
        try {
            fstream = new FileOutputStream(file);
            fileChannel = fstream.getChannel();
            fileLock =  fileChannel.tryLock();
            if (null != fileLock && fileLock.isValid()) {
                stream = new BufferedOutputStream(fstream);
                stream.write(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {

                if (null != fileLock) {
                    fileLock.release();
                }
//                if (null != fileChannel) {
//                    fileChannel.close();
//                }
                if (stream != null) {
                    stream.close();
                }
                if (null != fstream) {
                    fstream.close();
                }

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

在關閉get

FileChannel 會致使文件流被關閉,特別是寫較小文件時候,這個說明JDK8中,這個不須要去手動關閉
相關文章
相關標籤/搜索