• Java IO 流--FileUtils 工具类封装


    IO流的操作写多了,会发现都已一样的套路,为了使用方便我们可以模拟commosIo 封装一下自己的FileUtils 工具类:

    1、封装文件拷贝:

    文件拷贝需要输入输出流对接,通过输入流读取数据,然后通过输出流写出数据,封装代码如下:
    
    /**
    	 * 对接输入输出流
    	 * 
    	 * @param is
    	 * @param os
    	 */
    	public static void copy(InputStream is, OutputStream os) {
    		try {
    			byte[] flush = new byte[1024];
    			int len = -1;
    			while ((len = is.read(flush)) != -1) {
    				os.write(flush, 0, len);
    			}
    			os.flush();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			colse(os, is);//后面会封装关闭方法
    		}
    	}
    

    2、封装关闭流的操作

    IO 流都继承Closeable接口,所以我们可以使用接口传参,传入可变参数封装:
    
    /**
    	 * 释放资源
    	 * 
    	 * @param ios
    	 */
    	public static void colse(Closeable... ios) {
    		for (Closeable io : ios) {
    			try {
    				if (io != null) {
    					io.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    

    3、使用java 新特性 try…with…resource 写法不用考虑释放问题

    使用 try…with…resource 写法就不用封装close方法了直接对接输入输出流即可:

    /**
    	 * 对接输入输出流
    	 * 
    	 * @param is
    	 * @param os
    	 */
    	public static void copy(InputStream is, OutputStream os) {
    		try(InputStream ins = is; OutputStream ous = os) {
    			byte[] flush = new byte[1024];
    			int len = -1;
    			while ((len = ins.read(flush)) != -1) {
    				ous.write(flush, 0, len);
    			}
    			ous.flush();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} 
    	}
    

    4、测试代码

    public static void main(String[] args) {
    		// 文件到文件
    		try {
    			InputStream is = new FileInputStream("src/abc.txt");
    			OutputStream os = new FileOutputStream("src/abc-copy.txt");
    			copy(is, os);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    
    		// 文件到字节数组
    		byte[] datas = null;
    		try {
    			InputStream is = new FileInputStream("src/1.jpg");
    			ByteArrayOutputStream os = new ByteArrayOutputStream();
    			copy(is, os);
    			datas = os.toByteArray();
    			System.out.println(datas.length);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		// 字节数组到文件
    		try {
    			InputStream is = new ByteArrayInputStream(datas);
    			OutputStream os = new FileOutputStream("src/1-copy.jpg");
    			copy(is, os);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    

    我使用以上代码测试,两种封装都OK。

    重视基础,才能走的更远。
  • 相关阅读:
    免费申请域名
    分享学习linux网站
    二分法
    node 解决存储xss风险报告
    cf987f AND Graph
    loj2587 「APIO2018」铁人两项
    luogu3830 [SHOI2012]随机树
    luogu3343 [ZJOI2015]地震后的幻想乡
    bzoj2560 串珠子
    luogu3317 [SDOI2014]重建
  • 原文地址:https://www.cnblogs.com/xzlf/p/12681536.html
Copyright © 2020-2023  润新知