byte[]转成String的时候,请用BASE64来转码,否则会因为字符转换问题(不是所有的byte组合都能映射为char),导致内容丢失。 反之也用BASE64来重新得到byte[]。 二进制数据要转成字符串来传输是需要经过编码(例如BASE64)处理才可以的; 1.在发送端用BASE64Encoder将二进制数据编码成字符串后再发送; byte[] bt = <bt是读取到的图片的二制数据>; String temp = new sun.misc.BASE64Encoder().encodeBuffer(bt); 2.在接收端用BASE64Decoder对接收到的字符串解码成二进制数据;再输出生成图片; byte[] bt = new sun.misc.BASE64Decoder().decodeBuffer(temp); BASE64编码参见: http://baike.baidu.com/view/1485202.htm 例子: import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import junit.framework.TestCase; public class Debug extends TestCase { public void test() throws Exception { //1.在发送端用BASE64Encoder将二进制数据编码成字符串后再发送; String srcfile = "G:/workspace/hzjx_wsdl/WebContent/images/wj.jpg" ; byte [] bt_src = readFile(srcfile); String temp = new sun.misc.BASE64Encoder().encodeBuffer(bt_src); // .....<webservice传输 temp 过程> //2.在接收端用BASE64Decoder对接收到的字符串解码成二进制数据;再输出生成图片; byte [] bt_tag = new sun.misc.BASE64Decoder().decodeBuffer(temp); String tagfile = "G:/abcde.jpg" ; saveToFile(bt_tag, tagfile); System.out.println( "请检查目标文件<" +tagfile+ ">是否与源文件<" +srcfile+ ">的内容肯定是相同的!" ); System.out.println( "内容相同证明Base64编码与解码处理过程肯定是正确的!" ); } public static byte [] readFile(String filePath) { byte [] arr_result = null ; InputStream in = null ; ByteArrayOutputStream fout = new ByteArrayOutputStream( 8192 ); try { in = new FileInputStream(filePath); BufferedInputStream fin = new BufferedInputStream(in, 8192 ); byte [] data = new byte [ 8192 ]; int count = 0 ; while (count >= 0 ) { count = fin.read(data); if (count > 0 ) { fout.write(data, 0 , count); } } arr_result = fout.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null ) try {in.close();} catch (Exception ex){} if (fout != null ) try {fout.close();} catch (Exception ex){} } return arr_result; } public static void saveToFile( byte [] bt, String filePath) { OutputStream os = null ; try { File savefile = new File(filePath); os = new FileOutputStream(savefile); os.write(bt); } catch (IOException e) { e.printStackTrace(); } finally { if (os != null ){ try {os.close();} catch (Exception ex){}} } } }
|
|