• Java IO3 把一个图片写进txt,再写出还原图片


    package com.demo.zmz;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedWriter;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Base64;
    
    public class Base64Test {
    
    	public static void main(String[] args) {		
    		// 编码
    		encodeBase64();	
    		
    		// 解码	
    		dcodeBase64();
    	}
    	private static void dcodeBase64() {
    		// TODO Auto-generated method stub
    		try (BufferedInputStream in = new BufferedInputStream(new FileInputStream("a.txt"));
    				BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("aa.jpg"))) {
    			// RTFM 
    			//内存数组,输出流,写入buf用
    			ByteArrayOutputStream ramArray = new ByteArrayOutputStream();
    			
    			byte[] buf = new byte[1024*4];
    			int size;
    			while (-1 != (size = in.read(buf))) {
    				ramArray.write(buf, 0, size);
    			}
    			// 获得所有数据
    			byte[] data = ramArray.toByteArray();
    			//获取编码器-->返回字符串
    			byte[] img = Base64.getDecoder().decode(data);
    			
    			out.write(img);
    			System.out.println("ok");
    			
    		} catch (IOException e) {
    			
    		}
    	}
    	
    	private static void encodeBase64() {
    		
    		try (BufferedInputStream in = new BufferedInputStream(new FileInputStream("11111.jpg"));
    				BufferedWriter out = new BufferedWriter(new FileWriter("a.txt"))) {
    			// RTFM 
    			//内存数组,输出流,写入buf用
    			ByteArrayOutputStream ramArray = new ByteArrayOutputStream();
    			
    			byte[] buf = new byte[1024*4];
    			int size;
    			while (-1 != (size = in.read(buf))) {
    				ramArray.write(buf, 0, size);
    			}
    			// 获得所有数据
    			byte[] data = ramArray.toByteArray();
    			//获取编码器-->返回字符串
    			String s = Base64.getEncoder().encodeToString(data);
    			System.out.println(s);
    			
    			out.write(s);
    			
    		} catch (IOException e) {
    			
    		}
    	}
    }


    inputstream和outputstream是字节流,writer和reader是字符流

  • 相关阅读:
    es6
    ES6
    ES6
    css3
    滚动穿透的6种解决方案【已自测】
    css特效
    css布局
    css布局
    js
    【消灭代办】第5周
  • 原文地址:https://www.cnblogs.com/zhangmingzhao/p/7256599.html
Copyright © 2020-2023  润新知