关闭

使用NIO的FileChannel和ByteBuffer高效读取文件

标签: ibmbufferstringclass
10231人阅读 评论(2) 收藏 举报
分类:

http://hi.baidu.com/boywell/blog/item/658d143f730a553770cf6ccd.html

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


public class ReadWriteCompare
{

public static void main(String[] args) throws IOException
{
FileInputStream fileInputStream = new FileInputStream("f:"+ File.separator +"IBM e-Mentor Program Kickoff Night 1105.pdf");
FileOutputStream fileOutputStream = new FileOutputStream("f:" + File.separator + "test.pdf");
   FileChannel inChannel = fileInputStream.getChannel();
FileChannel outChannel= fileOutputStream.getChannel();

ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

   //Direct Buffer的效率会更高。
//   ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);     

   long start = System.currentTimeMillis();
while(true)
{
int eof = inChannel.read(byteBuffer);
if(eof == -1 ) break;
byteBuffer.flip();
    outChannel.write(byteBuffer);
byteBuffer.clear();
}
System.out.println("spending : " + (System.currentTimeMillis()-start));
inChannel.close();
outChannel.close();

}

}


0
1

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1351946次
    • 积分:10797
    • 等级:
    • 排名:第1550名
    • 原创:42篇
    • 转载:428篇
    • 译文:0篇
    • 评论:123条