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是字符流

posted @ 2017-06-02 00:38  Lawliet__zmz  阅读(222)  评论(0编辑  收藏  举报