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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM