FileChannel
Java NIO
中的FileChannel
是一个连接到文件的通道。可以通过文件通道读写文件,我们可以通过InputStream、OutputStream
或RandomAccessFile
来获取它的实例,FileChannel
无法设置为非阻塞模式。
FileOutputStream fos = new FileOutputStream("F:\\abcd.txt");
FileChannel fosChannel = fos.getChannel();
常用API
public int read(ByteBuffer dst)
:从通道读取数据并放到缓存区中public int write(ByteBuffer src)
:把缓冲区的数据写到通道中public long transferFrom(ReadableByteChannel src,long position,long count)
:从目标通道中复制数据到当前通道public long transferTo(long position,long count,WritableByteChannel target)
:把数据从当前通道复制给目标通道
使用案例
以下案例中会使用到
ByteBuffer
,它的底层的本质是一个数组,就是用来存放内容的,这里你可以看成是一个byte[]
,在本系列的上一节有专门针对ByteBuffer
进行讲解。
- 使用FileChannel.write方法像磁盘写入一个文件
public static void write() throws IOException { //通过输出流获取FileChannel FileOutputStream fos = new FileOutputStream("F:\\abc.txt"); FileChannel channel = fos.getChannel(); //文件中的内容 String str = "hello,it235"; //初始化空间,并将byte数组放入buffer中 ByteBuffer byteBuffer = ByteBuffer.allocate(1024); ByteBuffer put = byteBuffer.put(str.getBytes()); //翻转buffer,将缓冲区的数据写入通道 put.flip(); channel.write(put); fos.close(); }
- 使用FileChannel.read读取磁盘中的文件
public static void read() throws IOException { //IO流读取File File file = new File("F:\\abc.txt"); FileInputStream fis = new FileInputStream(file); //获取Channel FileChannel channel = fis.getChannel(); //文件内容长度 long length = file.length(); //实例化文件内容长度大小的缓冲区,用来临时存放读取出来的内容 ByteBuffer byteBuffer = ByteBuffer.allocate((int)length); channel.read(byteBuffer); //取出字节数组,并输出 System.out.println(new String(byteBuffer.array())); fis.close(); }
- 使用FileChannel.write+read方法进行文件的拷贝
/** * 拷贝文件 * @throws IOException */ public static void copy() throws IOException { //使用IO流读取文件,并拿到FileChannel File file = new File("F:\\abc.txt"); FileInputStream fis = new FileInputStream(file); FileChannel fisChannel = fis.getChannel(); //指定IO输出文件位置,并拿到FIleChannel FileOutputStream fos = new FileOutputStream("F:\\abcd.txt"); FileChannel fosChannel = fos.getChannel(); //声明缓冲区大小 ByteBuffer byteBuffer = ByteBuffer.allocate(1024); //循环读取并写入 while(true){ //从fisChannel中取出内容到buffer中 int read = fisChannel.read(byteBuffer); //如果没有内容了,则跳出循环 if(read == -1){ break; }else{ //因为使用的事buffer,所以需要翻转 byteBuffer.flip(); //使用fosChannel将buffer写入文件 fosChannel.write(byteBuffer); } //每次使用完byteBuffer后需要复位 byteBuffer.clear(); } fos.close(); fis.close(); }
- 使用FileChannel.transferFrom或transferTo进行文件的拷贝
public static void copyApi() throws IOException { //指定IO输入、输出文件位置 FileInputStream fis = new FileInputStream("F:\\abc.txt"); FileOutputStream fos = new FileOutputStream("F:\\abcd.txt"); //源文件Channel FileChannel sourceChannel = fis.getChannel(); //目标文件CHannel FileChannel destChannel = fos.getChannel(); //A:拷贝文件:从目标通道中复制数据到当前通道 destChannel.transferFrom(sourceChannel , 0 , sourceChannel.size()); //B:拷贝文件2:从源文件通道中复制数据到目标通道 //sourceChannel.transferTo(0 , sourceChannel.size() , destChannel ); //关闭资源 sourceChannel.close(); destChannel.close(); fos.close(); fis.close(); }
到此案例结束,接下来,我们来学习更多的内容…