说明
将文件拷贝方法封装为一个方法,使之适应普遍的应用场合。
代码
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
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、封装释放
* @author dxt
*
*/
public class FileUtils {
public static void main(String[] args){
//1. 测试对接输入输出流, 文件--->文件
try {
InputStream is = new FileInputStream("F:/myjava/IO_Study02/abc.txt");
OutputStream os = new FileOutputStream("F:/myjava/IO_Study02/abc_copy.txt");
copy(is, os);
} catch (IOException e) {
e.printStackTrace();
}
//2. 文件--->字节数组
byte[] datas = null;
try {
InputStream is = new FileInputStream("F:/myjava/IO_Study02/bg.jpg");
ByteArrayOutputStream os = new ByteArrayOutputStream();
copy(is, os);
datas = os.toByteArray();
System.out.println(datas.length);
} catch (IOException e) {
e.printStackTrace();
}
//3. 字节数组--->文件
try {
InputStream is = new ByteArrayInputStream(datas);
OutputStream os = new FileOutputStream("F:/myjava/IO_Study02/bg_copy.jpg");
copy(is, os);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 对接输入输出流
* @param fis
* @param fos
*/
public static void copy(InputStream fis, OutputStream fos){
try {
//3.1 分段读取操作
byte[] flush = new byte[1024];
int len = -1;
while((len = fis.read(flush)) != -1){
fos.write(flush, 0, len); //3.2 写操作
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} finally{
//4. 释放资源, 先打开的后关闭
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
/**
* IO流释放
* @param fis
* @param fos
*/
public static void close(InputStream fis, OutputStream fos){
try {
if(null != fos){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(null != fos){
fis.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
/**
* 重载
* @param io
*/
public static void close(Closeable... ios){ //...可变参数
for(Closeable io : ios){
try {
if(null != io){
io.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}