Java FileChannel文件的读写实例
一、概述:
文件通道FileChannel是用于读取,写入,文件的通道。FileChannel只能被InputStream、OutputStream、RandomAccessFile创建。使用fileChannel.transferTo()可以极大的提高文件的复制效率,他们读和写直接建立了通道,还能有效的避免文件过大导致内存溢出。
获取FileChannel的方法:
1、获取通道的一种方式是对支持通道的对象调用getChannel()方法。支持通道的类如下:
- FileInputStream
- FileOutputStream
- RandomAccessFile
- DatagramSocket
- Socket
- ServerSocket
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-本地文件写数据
@Testpublic void writeFile(){try {//1.字节输出流通向目标文件FileOutputStream fos = new FileOutputStream(new File("test.txt"));//2.得到字节输出流对应的通道ChannelFileChannel 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-本地文件读数据
@Testpublic 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-快速拷贝文件
@Testpublic void copyFile(){try {long starTime = System.currentTimeMillis();//1、创建输入文件流FileInputStream fis = new FileInputStream(new File("test.txt"));//2、得到输入channelFileChannel fisChannel = fis.getChannel();//3、创建输出文件流FileOutputStream fos = new FileOutputStream(new File("test2.txt"));//4、得到输出channelFileChannel fosChannel = fos.getChannel();//5、使用输入channel将文件转到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