大連城建設(shè)計研究院網(wǎng)站南昌seo顧問
一、概述:
文件通道FileChannel是用于讀取,寫入,文件的通道。FileChannel只能被InputStream、OutputStream、RandomAccessFile創(chuàng)建。使用fileChannel.transferTo()可以極大的提高文件的復(fù)制效率,他們讀和寫直接建立了通道,還能有效的避免文件過大導(dǎo)致內(nèi)存溢出。
獲取FileChannel的方法:
1、獲取通道的一種方式是對支持通道的對象調(diào)用getChannel()方法。支持通道的類如下:
- FileInputStream
- FileOutputStream
- RandomAccessFile
- DatagramSocket
- Socket
- ServerSocket
2、獲取通道的其他方式是使用Files類的靜態(tài)方法newByteChannel()獲取字節(jié)通道?;蛲ㄟ^通道的靜態(tài)方法open()打開并返回指定通道
二、FileChannel的常用方法
int read(ByteBuffer dst) 從Channel當(dāng)中讀取數(shù)據(jù)至ByteBuffer
long read(ByteBuffer[] dsts)將channel當(dāng)中的數(shù)據(jù)“分散”至ByteBuffer[]
int write(Bytesuffer src)將ByteBuffer當(dāng)中的數(shù)據(jù)寫入到Channel
long write(ByteBuffer[] srcs)將Bytesuffer[]當(dāng)中的數(shù)據(jù)“聚集”到Channel
long position()返回此通道的文件位置
FileChannel position(long p)設(shè)置此通道的文件位置
long size()返回此通道的文件的當(dāng)前大小
FileChannel truncate(long s)將此通道的文件截取為給定大小
void force(boolean metaData)強(qiáng)制將所有對此通道的文件更新寫入到存儲設(shè)備中
三、案例
1-本地文件寫數(shù)據(jù)
@Testpublic void writeFile(){try {//1.字節(jié)輸出流通向目標(biāo)文件FileOutputStream fos = new FileOutputStream(new File("test.txt"));//2.得到字節(jié)輸出流對應(yīng)的通道ChannelFileChannel channel = fos.getChannel();//3.分配緩存區(qū)ByteBuffer bf = ByteBuffer.allocate(1024);bf.put("tom is a hero".getBytes());//4.把緩存區(qū)切換為寫模式bf.flip();//5.輸出數(shù)據(jù)到文件channel.write(bf);channel.close();System.out.println("完成數(shù)據(jù)寫入..........");} catch (Exception e) {throw new RuntimeException(e);}}
2-本地文件讀數(shù)據(jù)
@Testpublic void readFile(){try {//1.定義一個文件字節(jié)輸入流與源文件接通FileInputStream fos = new FileInputStream(new File("test.txt"));//2.需要得到文件字節(jié)輸入流的文件通道FileChannel channel = fos.getChannel();//3.定義一個緩存區(qū)ByteBuffer bf = ByteBuffer.allocate(1024);//4.讀取數(shù)據(jù)到緩存區(qū)channel.read(bf);//5、歸位bf.flip();//6.讀取出緩存區(qū)中的數(shù)據(jù)并輸出即可String s = new String(bf.array(), 0, bf.remaining());channel.close();System.out.println("讀取內(nèi)容.........." + s);} catch (Exception e) {throw new RuntimeException(e);}}
3-快速拷貝文件
@Testpublic void copyFile(){try {long starTime = System.currentTimeMillis();//1、創(chuàng)建輸入文件流FileInputStream fis = new FileInputStream(new File("test.txt"));//2、得到輸入channelFileChannel fisChannel = fis.getChannel();//3、創(chuàng)建輸出文件流FileOutputStream fos = new FileOutputStream(new File("test2.txt"));//4、得到輸出channelFileChannel fosChannel = fos.getChannel();//5、使用輸入channel將文件轉(zhuǎn)到fosChannelfisChannel.transferTo(0, fisChannel.size(), fosChannel);fis.close();fos.close();fisChannel.close();fosChannel.close();long endTime = System.currentTimeMillis();System.out.println("耗時=" + (endTime - starTime) + "ms");} catch (IOException e) {throw new RuntimeException(e);}}
四、源碼下載
https://gitee.com/charlinchenlin/store-pos