Byte數組和字符串相互轉換的問題


第一:需求:將文件轉成byte數組,之后轉成字符串返回。過濾器接收到響應內容后,需要將響應的內容轉成byte數組。

第二:我剛開始的做法:

Controller:
byteArr = ConversionUtil.file2Byte(filePath); result = new String(byteArr,"utf-8");

filter:
String content = wrapResponse.getContent();
responseBodyMw = new BASE64Encoder().encode(content.getBytes("utf-8"));

結果:返回的String,和接收到的字符串不一樣。

原因:文件轉成二進制數組后,不是16進制的,所以不能采用newString  這種方式轉成字符串。

第三:現在的做法,寫了一個String和Byte轉換的工具類,具體代碼:

/** * @Author: kiki * @Date: 2018/12/26 */
public class ByteConvertUtil { public static String bytesToHexString(byte[] bArr) { StringBuffer sb = new StringBuffer(bArr.length); String sTmp; for (int i = 0; i < bArr.length; i++) { sTmp = Integer.toHexString(0xFF & bArr[i]); if (sTmp.length() < 2){ sb.append(0); } sb.append(sTmp.toUpperCase()); } return sb.toString(); } /** * hex字符串轉byte數組 * @param inHex 待轉換的Hex字符串 * @return 轉換后的byte數組結果 */
    public static byte[] hexToByteArray(String inHex){ int hexlen = inHex.length(); byte[] result; if (hexlen % 2 == 1){ //奇數
            hexlen++; result = new byte[(hexlen/2)]; inHex="0"+inHex; }else { //偶數
            result = new byte[(hexlen/2)]; } int j=0; for (int i = 0; i < hexlen; i+=2){ result[j]=(byte)Integer.parseInt(inHex.substring(i,i+2),16); j++; } return result; } }

說明:字符轉換時,直接使用就OK啦。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM