封装拷贝
封装释放
可变参数(typeName... name)
自动释放 try...with...resource
例:try(InputStream in=new FileInputStream(path);OutputStream out=new FileOutputStream(path)){
code...
}catch{}
不要写finally
public abstract class InputStream implements Closeable //Closeable 接口
public abstract class OutputStream implements Closeable, Flushable //Flushable 接口
package IOStudy;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 1.封装拷贝
* 2.封装释放
*
* 可变参数
* name(name... x)
*
* try...with...resource 自动释放
* @author pmc
*
*/
public class FileUtilsIO {
public static void main(String[] args) {
//文件到文件
try {
InputStream in=new FileInputStream("txt.txt");
OutputStream out = new FileOutputStream("txts.txt");
copy(in,out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//文件到字节数组
byte[] datas=null;
try {
InputStream in=new FileInputStream("abc.png");
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in,out);
datas=out.toByteArray();
System.out.println(datas.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//字节数组到文件
try {
InputStream in=new ByteArrayInputStream(datas);
OutputStream out = new FileOutputStream("abcd.png");
copy(in,out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 对接输入输出流
* @param in
* @param out
*/
private static void copy(InputStream in,OutputStream out){
try{
byte[] temp=new byte[1024];
int len = 0;
while((len=in.read(temp))!=-1){
out.write(temp,0,len);
}
out.flush();
}catch(IOException e){
e.printStackTrace();
}finally{
//先关闭写入,后关闭读取
close(in,out);
}
}
// private static void copyb(InputStream in,OutputStream out){
// try(in;out){
// byte[] temp=new byte[1024];
// int len = 0;
// while((len=in.read(temp))!=-1){
// out.write(temp,0,len);
// }
// out.flush();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
private static void copyc(String ins,String outs){
try(InputStream in=new FileInputStream(ins);OutputStream out=new FileOutputStream(outs)){//自动释放资源
byte[] temp=new byte[1024];
int len = 0;
while((len=in.read(temp))!=-1){
out.write(temp,0,len);
}
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
//资源释放
private static void close(InputStream in,OutputStream out){
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void close(Closeable... in){//可变参数,关闭
for(Closeable io:in){
if(io!=null){
try {
io.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void flush(Flushable... fulsh){//可变参数,刷新
for(Flushable fl:fulsh){
if(fl!=null){
try {
fl.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}