package cn.itcast_02;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* 复制图片
*
* 分析:
* 复制数据,如果我们用记事本打开并能够读懂,就用字符流,否则用字节流
* 通过该原理,我们知道应该采用字节流
* 而字节流有四种方式,所以我们做这道题目是有四种,推荐掌握第四种
* 1.高效流复制一次一个字节
* 2.高效流复制一次一个字节数组
* 3.基本字节流一次读取一个字符数组
* 4.基本字节流一次读取一个字符
*
* 数据源:E:\\流浪地球.jpg --- FileInputStream ---BufferedInPutStream
*
* 目的地:C:\\流浪地球.jpg --- FileOutputStream --- BuffereOutputStream
*/
public class 复制图片的4种方式 {
public static void main(String[] args) throws IOException {
//使用字符串作为路径
//String srcString = "E:\\流浪地球.jpg";
//String desString = "C:\\流浪地球.jpg ";
//使用File对象作为路径
File srcFile = new File("E:\\流浪地球.jpg");
File desFile = new File("E:\\流浪地球.jpg");
methon1(srcFile ,desFile);
methon2(srcFile ,desFile);
methon3(srcFile ,desFile);
methon4(srcFile ,desFile);
}
//基本字节流一次读取一个字符
private static void methon4(File srcFile, File desFile) throws IOException {
// 封装数据源
FileInputStream fi = new FileInputStream(srcFile);
//封装目的地
FileOutputStream fw = new FileOutputStream(desFile);
//复制
int by = 0;
while((by = fi.read()) != -1) {
fw.write(by);
}
//释放资源
fi.close();
fw.close();
}
//基本字节流一次读取一个字符数组
private static void methon3(File srcFile, File desFile) throws IOException {
// 封装数据源
FileInputStream fi = new FileInputStream(srcFile);
//封装目的地
FileOutputStream fw = new FileOutputStream(desFile);
//复制
byte[] by = new byte[1024];
int len = 0;
while((len = fi.read(by)) != -1) {
fw.write(by , 0 , len);
}
//释放资源
fi.close();
fw.close();
}
//高效流复制一次一个字节数组
private static void methon2(File srcFile, File desFile) throws IOException {
// 封装数据源
BufferedInputStream bi = new BufferedInputStream(new FileInputStream(srcFile));
//封装目的地
BufferedOutputStream bw =new BufferedOutputStream( new FileOutputStream(desFile));
//复制
byte[] by = new byte[1024];
int len = 0;
while((len = bi.read(by)) != -1) {
bw.write(by , 0 , len);
}
//释放资源
bi.close();
bw.close();
}
//高效流复制一次一个字节
private static void methon1(File srcFile, File desFile) throws IOException {
// 封装数据源
BufferedInputStream bi = new BufferedInputStream(new FileInputStream(srcFile));
//封装目的地
BufferedOutputStream bw =new BufferedOutputStream( new FileOutputStream(desFile));
//复制
int by = 0;
while((by = bi.read()) != -1) {
bw.write(by);
}
//释放资源
bi.close();
bw.close();
}
}
字节流之复制图片的4种方式
最新推荐文章于 2021-12-24 15:36:18 发布