天天看点

Java基础一:以字节流读取和写入文件

package xxx.yyy.zzz;

import java.io.*;

/**
 * 以字节流读取文件和写入文件
 */
public class IOUtil {

    //文件拷贝,批量读取
    public static void copyFile(File srcFile, File destFile) throws IOException{
        if (!srcFile.exists()){
            throw new IllegalArgumentException("文件:" + srcFile + "不存在");
        }
        if (!srcFile.isFile()){
            throw new IllegalArgumentException((srcFile + "不是文件"));
        }
        FileInputStream in = new FileInputStream((srcFile));
        FileOutputStream out = new FileOutputStream(destFile);
        byte[] buf = new byte[8*1024];
        int b;
        while ((b = in.read(buf, 0, buf.length)) != -1){
            out.write(buf, 0, b);
            out.flush();
        }
        in.close();
        out.close();
    }

    //带缓存的拷贝
    public static void copyByBuffer(File srcFile, File destFile) throws IOException{
        if (!srcFile.exists()){
            throw new IllegalArgumentException("文件:" + srcFile + "不存在");
        }
        if (!srcFile.isFile()){
            throw new IllegalArgumentException((srcFile + "不是文件"));
        }
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
        int c;
        while ((c = bis.read()) != -1){
            bos.write(c);
            bos.flush();
        }
        bis.close();
        bos.close();


    }

    //单字节拷贝
    public static void copyByByte(File srcFile, File destFile) throws IOException{
        if (!srcFile.exists()){
            throw new IllegalArgumentException("文件:" + srcFile + "不存在");
        }
        if (!srcFile.isFile()){
            throw new IllegalArgumentException((srcFile + "不是文件"));
        }
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        int c;
        while ((c = fis.read()) != -1){
            fos.write(c);
            fos.flush();
        }
        fis.close();
        fos.close();


    }
}