将.net传过来的二进制字符串转换成java的byte[]

    今天要用java调用一个同事写的.net的webService的一个方法,这个方法会返回文件的二进制字符串内容。他使用的方法如下所示:

 

Convert.ToBase64String((byte[])dr["attachment"]);

 

    我这边用java获得的二进制字符串内容要转成byte[]类型才能用IO操作保存到文件中,但是如果只是用得到的字符串简单的使用下面的方法转成byte[]的话,是错误 的。

 

 

byte[] content = element.getAttributeValue("content").getBytes();

 

    因为以上的代码没有对获得二进制字符串进行解码,因此使用上面的代码保存的文件是错误的。

 

    有两种方法可以对上面获得二进制内容进行解码:

 

   一、使用sun.misc.BASE64Decoder

 

    要使用sun.misc.BASE64Decoder对二进制字符串进行解码,这个类在jdk的rt.jar包里面。其内容如下所示:

 

/*
 * Copyright 1995-2000 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */
package sun.misc;

import java.io.OutputStream;
import java.io.PushbackInputStream;

import sun.misc.CEFormatException;
import sun.misc.CEStreamExhausted;
import sun.misc.CharacterDecoder;
import sun.misc.CharacterEncoder;

/**
 * This class implements a BASE64 Character decoder as specified in RFC1521.
 * 
 * This RFC is part of the MIME specification which is published by the Internet
 * Engineering Task Force (IETF). Unlike some other encoding schemes there is
 * nothing in this encoding that tells the decoder where a buffer starts or
 * stops, so to use it you will need to isolate your encoded data into a single
 * chunk and then feed them this decoder. The simplest way to do that is to read
 * all of the encoded data into a string and then use:
 * 
 * <pre>
 * byte mydata[];
 * BASE64Decoder base64 = new BASE64Decoder();
 * 
 * mydata = base64.decodeBuffer(bufferString);
 * </pre>
 * 
 * This will decode the String in <i>bufferString</i> and give you an array of
 * bytes in the array <i>myData</i>.
 * 
 * On errors, this class throws a CEFormatException with the following detail
 * strings:
 * 
 * <pre>
 * &quot;BASE64Decoder: Not enough bytes for an atom.&quot;
 * </pre>
 * 
 * @author Chuck McManis
 * @see CharacterEncoder
 * @see BASE64Decoder
 */

public class BASE64Decoder extends CharacterDecoder {

	/** This class has 4 bytes per atom */
	protected int bytesPerAtom() {
		return (4);
	}

	/** Any multiple of 4 will do, 72 might be common */
	protected int bytesPerLine() {
		return (72);
	}

	/**
	 * This character array provides the character to value map based on
	 * RFC1521.
	 */
	private final static char pem_array[] = {
	// 0 1 2 3 4 5 6 7
			'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0
			'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 1
			'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 2
			'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 3
			'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 4
			'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 5
			'w', 'x', 'y', 'z', '0', '1', '2', '3', // 6
			'4', '5', '6', '7', '8', '9', '+', '/' // 7
	};

	private final static byte pem_convert_array[] = new byte[256];

	static {
		for (int i = 0; i < 255; i++) {
			pem_convert_array[i] = -1;
		}
		for (int i = 0; i < pem_array.length; i++) {
			pem_convert_array[pem_array[i]] = (byte) i;
		}
	}

	byte decode_buffer[] = new byte[4];

	/**
	 * Decode one BASE64 atom into 1, 2, or 3 bytes of data.
	 */
	protected void decodeAtom(PushbackInputStream inStream,
			OutputStream outStream, int rem) throws java.io.IOException {
		int i;
		byte a = -1, b = -1, c = -1, d = -1;

		if (rem < 2) {
			throw new CEFormatException(
					"BASE64Decoder: Not enough bytes for an atom.");
		}
		do {
			i = inStream.read();
			if (i == -1) {
				throw new CEStreamExhausted();
			}
		} while (i == '\n' || i == '\r');
		decode_buffer[0] = (byte) i;

		i = readFully(inStream, decode_buffer, 1, rem - 1);
		if (i == -1) {
			throw new CEStreamExhausted();
		}

		if (rem > 3 && decode_buffer[3] == '=') {
			rem = 3;
		}
		if (rem > 2 && decode_buffer[2] == '=') {
			rem = 2;
		}
		switch (rem) {
		case 4:
			d = pem_convert_array[decode_buffer[3] & 0xff];
			// NOBREAK
		case 3:
			c = pem_convert_array[decode_buffer[2] & 0xff];
			// NOBREAK
		case 2:
			b = pem_convert_array[decode_buffer[1] & 0xff];
			a = pem_convert_array[decode_buffer[0] & 0xff];
			break;
		}

		switch (rem) {
		case 2:
			outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3)));
			break;
		case 3:
			outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3)));
			outStream.write((byte) (((b << 4) & 0xf0) | ((c >>> 2) & 0xf)));
			break;
		case 4:
			outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3)));
			outStream.write((byte) (((b << 4) & 0xf0) | ((c >>> 2) & 0xf)));
			outStream.write((byte) (((c << 6) & 0xc0) | (d & 0x3f)));
			break;
		}
		return;
	}
}

 

在使用的时候只要使用以下代码就可以将二进制字符串解码为byte[]:

 

public byte[] getContent(String binaryData){

		BASE64Decoder base64 = new BASE64Decoder();
		byte[] byteContent = base64.decodeBuffer(binaryData);
                return byteContent;
}

 

解码之后使用IO的操作方法就可以把二进制内容保存为文件:

 

/**  
	    * 将数据写入文件 
	    * @param data byte[] 
	    * @throws IOException 
	    */  
	 public static void writeFile(byte[] data,String filename){  
		 
		 try{
	     File file =new File(filename);  
	     BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(file));  
	     bufferedOutputStream.write(data);  
	     bufferedOutputStream.flush();
	     bufferedOutputStream.close();  
		 }catch(IOException e){
			e.printStackTrace(); 
		 }
	   
	 }
 

    二、使用apache的commons-codec 项目。

    因为上面的sun.misc.BASE64Decoder在jdk的rt.jar包中,对于没有安装jdk,只安装了jre的环境来说使用不方便。所以笔者倾向于使用apache的commons-codec项目。

 

在使用的时候只要使用以下代码就可以将二进制字符串解码为byte[]:

 

public byte[] getContent(String binaryData){

		Base64 base64 = new Base64();
		byte[] byteContent = base64.decode(binaryData);
                return byteContent;
}
 

解码之后使用IO的操作方法就可以把二进制内容保存为文件:

 

/**  
	    * 将数据写入文件 
	    * @param data byte[] 
	    * @throws IOException 
	    */  
	 public static void writeFile(byte[] data,String filename){  
		 
		 try{
	     File file =new File(filename);  
	     BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(file));  
	     bufferedOutputStream.write(data);  
	     bufferedOutputStream.flush();
	     bufferedOutputStream.close();  
		 }catch(IOException e){
			e.printStackTrace(); 
		 }
	   
	 }
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值