FileChannel与ByteBuffer的使用示例
生活随笔
收集整理的這篇文章主要介紹了
FileChannel与ByteBuffer的使用示例
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
?DirectByteBuffer直接內(nèi)存的使用場(chǎng)景和作用
生命周期長(zhǎng)的大對(duì)象,
減少java堆GC, 減少內(nèi)存copy
http://www.importnew.com/26334.html
?
1 public class DirectByteBufferTest { 2 3 4 @Test 5 public void test_copyFile() throws IOException { 6 ByteBuffer byteBuffer = ByteBuffer.allocateDirect(10);//100kbytes 7 FileChannel readChannel = FileChannel.open(new File("D:/in.txt").toPath()); 8 //out.txt必須已經(jīng)存在, writeChannel必須以WRITE方式打開 9 FileChannel writeChannel = FileChannel.open(new File("D:/out.txt").toPath(), StandardOpenOption.WRITE); 10 int read; 11 while ((read = readChannel.read(byteBuffer)) != -1) { 12 //buffer從讀切換到寫 13 byteBuffer.flip(); 14 // 打印信息必須放在flip后面, 否則decode出來(lái)的是上次read的結(jié)果.根據(jù)in.txt的字符編碼修改下面的ISO_8859_1 15 //System.out.println(read + "--" + StandardCharsets.ISO_8859_1.decode(byteBuffer)); 16 writeChannel.write(byteBuffer); 17 // 寫完之后清空緩沖區(qū),否則read=0一直死循環(huán) 18 byteBuffer.clear(); 19 } 20 writeChannel.close(); 21 readChannel.close(); 22 } 23 }?測(cè)試其他總結(jié):
ByteBuffer.allocateDirect緩沖區(qū)大小根據(jù)輸入文件的大小調(diào)整,但是太大時(shí)輸出性能也提高不了多少, 對(duì)于大文件,1M的緩存區(qū)應(yīng)該差不多了。對(duì)于超大文件, 應(yīng)該換成其他讀取方式轉(zhuǎn)載于:https://www.cnblogs.com/yszzu/p/9402051.html
總結(jié)
以上是生活随笔為你收集整理的FileChannel与ByteBuffer的使用示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java 时间转换去杠
- 下一篇: 线程队列 线程池 协程