Java-字节流读写实现复制文件
2020-09-25 475
Java-字节流读写实现复制文件
/**
* Java利用FileInputStream和FileOutputStream操作字节流实现复制文件
* @Author: www.itze.cn
* @Date: 2020/9/24 10:29
* @Email: 814565718@qq.com
* @param srcFile
* @param destFile
*/
public static void copyFile(File srcFile, File destFile) {
//判断原文件是否存在
if (!srcFile.exists()) {
throw new IllegalArgumentException("源文件:" + srcFile + "不存在!");
}
//判断原文件是否为一个文件
if (!srcFile.isFile()) {
throw new IllegalArgumentException(srcFile + "不是一个文件!");
}
try {
FileInputStream in = new FileInputStream(srcFile);
FileOutputStream out = new FileOutputStream(destFile);
/**
* 读取原文件,以字节流的形式读到byte数组,1024个字节=1KB
* 循环读取
* in.read()读到bytes数组中,位置从0-bytes.length
*/
byte[] bytes = new byte[10 * 1024];
int b; //b为读取到的字节长度
while ((b = in.read(bytes, 0, bytes.length)) != -1) {
//写入
out.write(bytes, 0, b);
out.flush();
}
//关闭
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
使用方法
public static void main(String[] args) {
copyFile(new File("D:\\a.png"), new File("D:\\b.png"));
}