四、java IO--使用字节流拷贝文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream
/**
 * 文件的拷贝
 * 1、建立连接
 * 2、选择流
 *              文件输入流  InputStream FileInputStream
                  文件输出流  OutputStream FileOutputStream
 * 3、操作:
 *                 循环{读取+写出} + 强制刷新
 * 4、释放资源
 * @author baba
 *
 */
public class CopyFile {
    public static void main(String[] args) {
        String srcPath = "F:/read.txt";
        String destPath = "F:/write.txt";
        copyFile(new File(srcPath),new File(destPath));
    }
    public static void copyFile(File src,File dest){
        
        if(! src.isFile()){ //当不是文件或者为null
            System.out.println("只能拷贝文件");
            try {
                throw new IOException("只能拷贝文件");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(dest.isDirectory()){    //不能建立于文件夹同名的文件
            System.out.println(dest.getAbsolutePath()+"不能建立于文件夹同名的文件");
            try {
                throw new IOException(dest.getAbsolutePath()+"不能建立于文件夹同名的文件");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //1、建立连接
        InputStream is =null;
        OutputStream os = null;
        try {
            //2、选择流
             is = new FileInputStream(src);
             os = new FileOutputStream(dest);
            //3、操作: 循环{读取+写出} + 强制刷新
            byte[] inData = new byte[1024];
            int len = 0;
            while(-1 != (len = is.read(inData))){    //读取文件
                os.write(inData, 0, len);    //每次以inData大小读取数据
            }
            os.flush();    //将存储在管道中的数据强制刷新出去
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件不存在!"); 
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取文件失败!");
        }finally {
            if (os != null)
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
}
原文地址:https://www.cnblogs.com/jiaoqiang/p/8378466.html