IO流之封装文件复制
实现两种功能的封装
1、封装拷贝(基于IO流的InputStream
和OutputStream
)
2、封装释放资源
封装拷贝
可以从文件到文件,也可以从文件到字节数组,或从字节数组到文件。
示例代码如下:
/**
* 拷贝
* 对接输入,输出流
* @param is
* @param os
*/
public static void copy(InputStream is, OutputStream os) {
try {
byte[] flush = new byte[3];
int len = -1;
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
close(is, os);
}
}
封装释放资源
使用IO流中共同实现的Closeable对所有的流进行关闭
/**
* 释放资源
*
* @param ios
*/
public static void close(Closeable... ios) {
for (Closeable io : ios) {
try {
if (io != null) {
io.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
主程序
main
public static void main(String[] args) {
// 文件到文件
try {
InputStream is = new FileInputStream("abc.txt");
OutputStream os = new FileOutputStream("abc_copy.txt");
copy(is, os);
} catch (IOException e) {
e.printStackTrace();
}
// 文件到字节数组
byte[] datas = null;
try {
InputStream is = new FileInputStream("ball.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(is, baos);
datas = baos.toByteArray();
System.out.println(datas.length);
} catch (IOException e) {
e.printStackTrace();
}
// 字节数组到文件
try {
OutputStream os = new FileOutputStream("ball_copy.jpg");
ByteArrayInputStream is = new ByteArrayInputStream(datas);
copy(is, os);
} catch (IOException e) {
e.printStackTrace();
}
}
Java7之后的try…with…resource方法
可以使用try…with…resource方法代替try,这样就可以自动关闭流而不需要手动输入额外代码 。
示例:
try(InputStream is = new FileInputStream(src);
OutputStream os = new FileOutputStream(dest)){
// TODO
} catch(IOException e){
e.printStackTrace();
}
使用此方法的封装拷贝文件的代码如下:
import java.io.*;
/**
* 1、封装拷贝
*
* @Author Nino 2019/10/20
*/
public class FileUtils2 {
public static void main(String[] args) {
// 文件到文件
try {
InputStream is = new FileInputStream("abc.txt");
OutputStream os = new FileOutputStream("abc_copy.txt");
copy(is, os);
} catch (IOException e) {
e.printStackTrace();
}
// 文件到字节数组
byte[] datas = null;
try {
InputStream is = new FileInputStream("ball.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(is, baos);
datas = baos.toByteArray();
System.out.println(datas.length);
} catch (IOException e) {
e.printStackTrace();
}
// 字节数组到文件
try {
OutputStream os = new FileOutputStream("ball_copy.jpg");
ByteArrayInputStream is = new ByteArrayInputStream(datas);
copy(is, os);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 复制文件
* 对接输入,输出流
* 释放资源时使用try...with...resource方法
* 这可以使得我们使用完流后自动释放流资源
* @param is
* @param os
*/
public static void copy(InputStream is, OutputStream os) {
try(is;os) {
byte[] flush = new byte[3];
int len = -1;
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}