package com.sxt.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** *1、 圖片讀取到字節數組 *2、 字節數組寫出到文件 * @author 裴新 * */ public class IOTest09 { public static void main(String[] args) { //圖片轉成字節數組 byte[] datas = fileToByteArray("p.png"); System.out.println(datas.length); byteArrayToFile(datas,"p-byte.png"); } /** * 1、圖片讀取到字節數組 * 1)、圖片到程序 FileInputStream * 2)、程序到字節數組 ByteArrayOutputStream */ public static byte[] fileToByteArray(String filePath) { //1、創建源與目的地 File src = new File(filePath); byte[] dest =null; //2、選擇流 InputStream is =null; ByteArrayOutputStream baos =null; try { is =new FileInputStream(src); baos = new ByteArrayOutputStream(); //3、操作 (分段讀取) byte[] flush = new byte[1024*10]; //緩沖容器 int len = -1; //接收長度 while((len=is.read(flush))!=-1) { baos.write(flush,0,len); //寫出到字節數組中 } baos.flush(); return baos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { //4、釋放資源 try { if(null!=is) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * 2、字節數組寫出到圖片 * 1)、字節數組到程序 ByteArrayInputStream * 2)、程序到文件 FileOutputStream */ public static void byteArrayToFile(byte[] src,String filePath) { //1、創建源 File dest = new File(filePath); //2、選擇流 InputStream is =null; OutputStream os =null; try { is =new ByteArrayInputStream(src); os = new FileOutputStream(dest); //3、操作 (分段讀取) byte[] flush = new byte[5]; //緩沖容器 int len = -1; //接收長度 while((len=is.read(flush))!=-1) { os.write(flush,0,len); //寫出到文件 } os.flush(); } catch (IOException e) { e.printStackTrace(); }finally { //4、釋放資源 try { if (null != os) { os.close(); } } catch (Exception e) { } } } }