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(); } } } }
相关文章推荐
- 下载文件或图片出错,显示Can not find a java.io.InputStream with the name [inputStream] in the invocation
- Java IO 四大附加接口、try-with-resource
- java中文件IO之图片的拷贝解析
- 文件下载Can not find a java.io.InputStream with the name [inputStream] in the invocation stack错误
- 黑马程序员——java IO实现文件拷贝
- (Struts2文件下载)Can not find a java.io.InputStream with the name [inputStream] in the invocation stack
- Java Io 之拷贝文件性能比较
- Java常用面试题16 用IO和NIO两种方式实现文件拷贝
- 深入理解 Java 中的 try-with-resource
- tomcat下载文件时,URL含有文字参数与空格参数出错(java.io.FileNotFoundException错误) 解决方法(转)
- 遇到问题----struts2文件下载出现Can not find a java.io.InputStream with the name的错误
- IO_对象处理流_序列化反序列化_关闭流jdk1.7try-with-resourceJAVA159-160
- mybatis进行测试时找不到配置文件:java.io.IOException: Could not find resource config/SqlMapConfig.xml 的解决
- Java进阶知识点3:更优雅地关闭资源 - try-with-resource及其异常抑制
- java io文件的切割与合并(图片)
- 深入理解Java try-with-resource【细节2】
- 黑马程序员-JAVA高级视频_IO输入与输出-19天-8(拷贝图片)
- Java IO和Java NIO在文件拷贝上的性能差异分析
- struts2文件下载出现Can not find a java.io.InputStream with the name的错误
- java IO之字节流和字符流-Reader和Writer以及实现文件复制拷贝