一、概述:

文件通道FileChannel是用于读取,写入,文件的通道。FileChannel只能被InputStream、OutputStream、RandomAccessFile创建。使用fileChannel.transferTo()可以极大的提高文件的复制效率,他们读和写直接建立了通道,还能有效的避免文件过大导致内存溢出。

获取FileChannel的方法:

1、获取通道的一种方式是对支持通道的对象调用getChannel()方法。支持通道的类如下:

FileInputStreamFileOutputStreamRandomAccessFileDatagramSocketSocketServerSocket

2、获取通道的其他方式是使用Files类的静态方法newByteChannel()获取字节通道。或通过通道的静态方法open()打开并返回指定通道

二、FileChannel的常用方法

int read(ByteBuffer dst) 从Channel当中读取数据至ByteBuffer

long read(ByteBuffer[] dsts)将channel当中的数据“分散”至ByteBuffer[]

int write(Bytesuffer src)将ByteBuffer当中的数据写入到Channel

long write(ByteBuffer[] srcs)将Bytesuffer[]当中的数据“聚集”到Channel

long position()返回此通道的文件位置

FileChannel position(long p)设置此通道的文件位置

long size()返回此通道的文件的当前大小

FileChannel truncate(long s)将此通道的文件截取为给定大小

void force(boolean metaData)强制将所有对此通道的文件更新写入到存储设备中

三、案例

1-本地文件写数据

@Test

public void writeFile(){

try {

//1.字节输出流通向目标文件

FileOutputStream fos = new FileOutputStream(new File("test.txt"));

//2.得到字节输出流对应的通道Channel

FileChannel channel = fos.getChannel();

//3.分配缓存区

ByteBuffer bf = ByteBuffer.allocate(1024);

bf.put("tom is a hero".getBytes());

//4.把缓存区切换为写模式

bf.flip();

//5.输出数据到文件

channel.write(bf);

channel.close();

System.out.println("完成数据写入..........");

} catch (Exception e) {

throw new RuntimeException(e);

}

}

2-本地文件读数据

@Test

public void readFile(){

try {

//1.定义一个文件字节输入流与源文件接通

FileInputStream fos = new FileInputStream(new File("test.txt"));

//2.需要得到文件字节输入流的文件通道

FileChannel channel = fos.getChannel();

//3.定义一个缓存区

ByteBuffer bf = ByteBuffer.allocate(1024);

//4.读取数据到缓存区

channel.read(bf);

//5、归位

bf.flip();

//6.读取出缓存区中的数据并输出即可

String s = new String(bf.array(), 0, bf.remaining());

channel.close();

System.out.println("读取内容.........." + s);

} catch (Exception e) {

throw new RuntimeException(e);

}

}

3-快速拷贝文件

@Test

public void copyFile(){

try {

long starTime = System.currentTimeMillis();

//1、创建输入文件流

FileInputStream fis = new FileInputStream(new File("test.txt"));

//2、得到输入channel

FileChannel fisChannel = fis.getChannel();

//3、创建输出文件流

FileOutputStream fos = new FileOutputStream(new File("test2.txt"));

//4、得到输出channel

FileChannel fosChannel = fos.getChannel();

//5、使用输入channel将文件转到fosChannel

fisChannel.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

参考链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: