Java实现编码解码助手工具,基本覆盖常用互转

import com.google.common.base.Utf8;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.tomcat.util.buf.Utf8Encoder;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 
 * @date 
 */
public class EncodeDecodeUtils {

    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String encode_decode(String content,String type){

        String result = "";

        if("CN|Unicode".equals(type)){//中文转Unicode

            char[] utfBytes = content.toCharArray();
            String unicodeBytes = "";
            for (int i = 0; i < utfBytes.length; i++) {
                String hexB = Integer.toHexString(utfBytes[i]);
                if (hexB.length() <= 2) {
                    hexB = "00" + hexB;
                }
                unicodeBytes = unicodeBytes + "\\u" + hexB;
            }

            result = result + unicodeBytes;

        }else if("Unicode|CN".equals(type)){//Unicode转中文

            Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
            Matcher matcher = pattern.matcher(content);
            char ch;
            while (matcher.find()) {
                ch = (char) Integer.parseInt(matcher.group(2), 16);
                content = content.replace(matcher.group(1), ch + "");
            }

            result = result + content;

        }else if("ASCII|Unicode".equals(type)){//ASCII转Unicode
 
            String clearStr = content.replace("&#","");
            String[] asciiArr = clearStr.split(";");
            for(String ascii : asciiArr){
                char character = (char) Integer.parseInt(ascii); 
                String str = Character.toString(character);  
                result = result + str;
            }

        }else if("Unicode|ASCII".equals(type)){//Unicode转ASCII

            char[] chars = content.toCharArray();

            for (int i = 0; i < chars.length; i++) {
                int asciiValue = (int) chars[i];
                result = result + "&#" + asciiValue + ";";
            }


        }else if("CN|UTF8".equals(type)){//中文转UTF-8

            char[] utfBytes = content.toCharArray();
            String unicodeBytes = "";
            for (int i = 0; i < utfBytes.length; i++) {
                String hexB = Integer.toHexString(utfBytes[i]);
                if (hexB.length() <= 2) {
                    hexB = "00" + hexB;
                }
                unicodeBytes = unicodeBytes + "&#x" + hexB + ";";
            }

            result = result + unicodeBytes;

        }else if("UTF8|CN".equals(type)){//UTF-8转中文

            StringBuffer tmp = new StringBuffer();
            tmp.ensureCapacity(content.length());
            int  lastPos=0,pos=0;
            char ch;
            content = content.replace("&#x","%u").replace(";","");
            while (lastPos<content.length()){
                pos = content.indexOf("%",lastPos);
                if (pos == lastPos){
                    if (content.charAt(pos+1)=='u'){
                        ch = (char)Integer.parseInt(content.substring(pos+2,pos+6),16);
                        tmp.append(ch);
                        lastPos = pos+6;
                    }else{
                        ch = (char)Integer.parseInt(content.substring(pos+1,pos+3),16);
                        tmp.append(ch);
                        lastPos = pos+3;
                    }
                } else{
                    if (pos == -1){
                        tmp.append(content.substring(lastPos));
                        lastPos=content.length();
                    } else{
                        tmp.append(content.substring(lastPos,pos));
                        lastPos=pos;
                    }
                }
            }
            result = tmp.toString();

        }else if("url|Encode".equals(type)){//UrlEncode编码

            try {

                result = result + URLEncoder.encode(content, "UTF-8").replace("+", "%20");

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }else if("url|Decode".equals(type)){//UrlDecode解码

            try {

                result = result + URLDecoder.decode(content, "UTF-8");

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }else if("CN|HEX".equals(type)){//中文转HEX编码

            char[] chars = Hex.encodeHex(content.getBytes());
            for(char c : chars){
                result = result + c;
            }

        }else if("HEX|CN".equals(type)){//HEX编码转中文

            try {

                byte[] bytes = Hex.decodeHex(content);
                result = result + new String(bytes);

            } catch (DecoderException e) {
                e.printStackTrace();
            }

        }else if("Base64|Encode".equals(type)){//Base64编码


            Base64.Encoder encoder = Base64.getEncoder();

            try {
                byte[] textByte = content.getBytes("UTF-8");
                String encodedText = encoder.encodeToString(textByte);
                result = result + encodedText;
            } catch (UnsupportedEncodingException e) {
                System.out.println("base64编码出错 :" + e.getMessage());
            }

        }else if("Base64|Decode".equals(type)){//Base64解码

            Base64.Decoder decoder = Base64.getDecoder();
            try {
                String text = new String(decoder.decode(content), "UTF-8");
                result = result +  text;
            } catch (UnsupportedEncodingException e) {
                System.out.println("base64解码出错 :" + e.getMessage());
            }
        }else if("Base64|HEX".equals(type)){

            Base64.Decoder decoder = Base64.getDecoder();
            byte[] bytes = decoder.decode(content);

            StringBuilder stringBuilder = new StringBuilder();
            int a = 0;
            int index = 0;
            for(byte b : bytes) { // 使用除与取余进行转换
                if(b < 0) {
                    a = 256 + b;
                } else {
                    a = b;
                }
                stringBuilder.append("0x" + HEX_CHAR[a / 16] + HEX_CHAR[a % 16] + ",");
            }

            result = stringBuilder.toString();

            if(result.length() > 0){
                result = "[" + result.substring(0,result.length()-1) + "]";
            }

        }else if("HEX|Base64".equals(type)){

            content = content.replace("[","")
                    .replace("]","")
                    .replace("0x","")
                    .replace(",","");

            byte[] bytes = new byte[content.length() / 2];
            for(int i = 0; i < content.length() / 2; i++) {
                String subStr = content.substring(i * 2, i * 2 + 2);
                bytes[i] = (byte) Integer.parseInt(subStr, 16);
            }

            Base64.Encoder encoder = Base64.getEncoder();
            String encodedText = encoder.encodeToString(bytes);
            result = result + encodedText;
        }

        return result;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值