zoukankan      html  css  js  c++  java
  • JavaSE:NIO

    使用FileChannel完成文件的复制

    1. 图解

    2. 代码

     1 import  java.io.FileInputStream;
     3 import  java.io.FileNotFoundException;
     5 import  java.io.FileOutputStream;
     6 
     7 import  java.io.IOException;
     8 
     9 import  java.nio.ByteBuffer;
    10 
    11 import  java.nio.channels.FileChannel;
    12 
    13 
    14 
    15 public class Channel完成文件复制 {
    16 
    17   main() {
        
        // 创建输入流和输出流 (依赖于IO流获取channel)
    21     // 输入流 22     FileInputStream fileInputStream = new FileInputStream("C:\Users\sunzh\Desktop\wxy.png"); 23     // 输出流 24     FileOutputStream fileOutputStream = new FileOutputStream("C:\Users\sunzh\Desktop\lagou_myself\nio\复制.png"); 25      26   // 通过IO流, 获取channel通道
    27     FileChannel f1 = fis.getChannel(); 28     FileChannel f2 = fos.getChannel(); 29 30 31     // 创建缓冲区 32     ByteBuffer buffer = ByteBuffer.allocate(1024); 33      34     // 循环
          // 利用通道f1, 将内容读入到buffer中
    35     while(f1.read(buffer) != -1) { 36 37       // 切换模式, 改变position和limit的位置 (limit = 原position, position = 0) 38       buffer.flip();
    39       // 输出到f2中 41       f2.write(buffer); 42 43       // 还原所有指针(变量 position, limit ... )的位置 45       buffer.clear();   46 47     } 48     // 关流 50     fos.close(); 51     fis.close(); 54 }
  • 相关阅读:
    Leetcode-113 Path Sum II(路径总和 II)
    Leetcode-946 验证栈序列(Validate Stack Sequences)
    Leetcode-945 Minimum Increment to Make Array Unique(使数组唯一的最小增量)
    UVa-10129 Play on Words
    UVa-10305 Ordering Tasks
    UVa-816 Abbott's Revenge
    UVa-1103 Ancient Messages
    种子填充(flood fill)
    内存池
    Leetcode-942 DI String Match(增减字符串匹配)
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/14958942.html
Copyright © 2011-2022 走看看