您的位置:首页 > 编程语言 > Java开发

java _io_文件的拷贝、图片的拷贝、可变参数、try...with...resource面向

2019-07-25 17:05 1726 查看

public static void close(Closeable... io) //可变参数,相当于数组

Closeable... io //可变参数,使用时相当于数组(for循环遍历)
Closeable 输入输出流实现的接口,在释放资源时使用
try...with..resource 自动释放资源工具
在try后接(is;os),其他的不变,会自动释放资源,不用管先后顺序(手动书写关闭时要先打开的后关闭)
try(InputStream iso=is;OutputStream oso=os){}//jdk9以下需要手动写入流的声明
try(is;os){} //jdk9以上自动生成流的声明

public class el {

public static void main(String[]args)
{
//文件拷贝
try {
InputStream is=new FileInputStream("C:\\Users\\10853\\eclipse-workspace\\hell\\src\\hell\\abc");
OutputStream os =new FileOutputStream("D:/d/b.txt");

copy(is,os);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data=null;
//图片到字节数组
try {
InputStream is=new FileInputStream("C:\\Users\\10853\\eclipse-workspace\\hell\\linux学习路线.png");
ByteArrayOutputStream os=new ByteArrayOutputStream();

copy(is,os);
data=os.toByteArray();
System.out.println(data.length);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//字节数组到文件
try {

ByteArrayInputStream is =new ByteArrayInputStream(data);
OutputStream os=new FileOutputStream("D:/d/q");
}catch(FileNotFoundException e)
{
e.printStackTrace();
}

}

public static void copy(InputStream is,OutputStream os)
{                                                   //释放资源工具,不用考虑顺序
try(InputStream iso=is;OutputStream oso=os) {   //用到了try...with...resource自动释放资源
//jdk版本9以上为try(is;os){}
//jdk版本9以下需要重新声明流try(InputStream iso=is;OutputStream oso=os)
//{}

byte[] flush=new byte[1024];
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);
}

}

//封装释放资源,用到了可变数组和输入输出流实现的接口Closeable
public static void close(Closeable... io) //可变参数,相当于数组
{
for(Closeable i:io)
{
try {
if(null!=i) {
i.close();
}
}catch(IOException e)
{
e.printStackTrace();
}
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐