1 import java.io.*; 2 3 public class TestIO008 { 4 public static void main(String[] args) { 5 //图片转成字节数组 6 byte[] datas = fileToByteArray("女子.jpg"); 7 System.out.println(datas.length); 8 byteArrayToFile(datas,"美女13.jpg"); 9 } 10 /** 11 * 1、图片读取到字节数组 12 * 1)、图片到程序 FileInputStream 13 * 2)、程序到字节数组 ByteArrayOutputStream 14 */ 15 public static byte[] fileToByteArray(String filePath) { 16 //1、创建源与目的地 17 File src = new File(filePath); 18 //2、选择流 19 InputStream is =null; 20 ByteArrayOutputStream baos =null; 21 try { 22 is =new FileInputStream(src); 23 baos = new ByteArrayOutputStream(); 24 //3、操作 (分段读取) 25 byte[] flush = new byte[1024*10]; //缓冲容器 26 int len = -1; //接收长度 27 while((len=is.read(flush))!=-1) { 28 baos.write(flush,0,len); //写出到字节数组中 29 } 30 baos.flush(); 31 return baos.toByteArray(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 }finally { 35 //4、释放资源 36 try { 37 if(null!=is) { 38 is.close(); 39 } 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 } 44 return null; 45 } 46 /** 47 * 2、字节数组写出到图片 48 * 1)、字节数组到程序 ByteArrayInputStream 49 * 2)、程序到文件 FileOutputStream 50 */ 51 public static void byteArrayToFile(byte[] src,String filePath) { 52 //1、创建源 53 File dest = new File(filePath); 54 //2、选择流 55 InputStream is =null; 56 OutputStream os =null; 57 try { 58 is =new ByteArrayInputStream(src); 59 os = new FileOutputStream(dest); 60 //3、操作 (分段读取) 61 byte[] flush = new byte[5]; //缓冲容器 62 int len = -1; //接收长度 63 while((len=is.read(flush))!=-1) { 64 os.write(flush,0,len); //写出到文件 65 } 66 os.flush(); 67 } catch (IOException e) { 68 e.printStackTrace(); 69 }finally { 70 //4、释放资源 71 try { 72 if (null != os) { 73 os.close(); 74 } 75 } catch (IOException e) { 76 e.printStackTrace(); 77 } 78 } 79 } 80 }