IO流之copy

IO流之copy
 
package com.io.outputstream_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 完成文件copy
 */
public class FileCopy {
    public static void main(String[] args) {
        //将d:\\cat.jpg拷贝到c:\\
        //思路分析:
        //1.创建文件的输出流,将文件读入到程序
        //2.创建文件的输出流,将读取到的文件数据,写入到指定的文件
        String srcFilePath="d:\\cat.jpg";
        String destFilePath="d:\\cat2.jpg";
        FileOutputStream fileOutputStream=null;
        FileInputStream fileInputStream=null;
        try{
            fileInputStream=new FileInputStream(srcFilePath);
            fileOutputStream = new FileOutputStream(destFilePath);
            //定义一个字节数组,提高读取效果
            byte[] buf = new byte[1024];
            int readLen=0;
            while ((readLen=fileInputStream.read(buf))!=-1){
                //读取到后就写入到文件 通过 fileOutputStream
                //即,是一边读一边写
                fileOutputStream.write(buf,0,readLen);//一定要使用这个方法
            }
            System.out.println("拷贝成功");
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try {
                if (fileInputStream!=null){
                    fileInputStream.close();
                }
                if (fileOutputStream!=null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}

 


 

 

 

 

 

posted @ 2022-04-28 21:27  胖虎9  阅读(58)  评论(0)    收藏  举报