left Pad Chinese To Byte Length - Java Internationalization

Java examples for Internationalization:Chinese

Description

left Pad Chinese To Byte Length

Demo Code


//package com.java2s;
import java.io.UnsupportedEncodingException;

public class Main {

    public static String leftPad4ChineseToByteLength(String srcStr,
            int totalByteLength, String padStr) {
        if (srcStr == null) {
            return null;
        }/* w  ww.j a  v a  2 s  . c om*/
        int srcByteLength = srcStr.getBytes().length;

        if (padStr == null || "".equals(padStr)) {
            padStr = " ";
        } else if (padStr.getBytes().length > 1 || totalByteLength <= 0) {
            throw new RuntimeException("");
        }
        StringBuilder rtnStrBuilder = new StringBuilder();
        if (totalByteLength >= srcByteLength) {
            for (int i = 0; i < totalByteLength - srcByteLength; i++) {
                rtnStrBuilder.append(padStr);
            }
            rtnStrBuilder.append(srcStr);
        } else {
            byte[] rtnBytes = new byte[totalByteLength];
            try {
                System.arraycopy(srcStr.getBytes("GBK"), 0, rtnBytes, 0,
                        totalByteLength);
                rtnStrBuilder.append(new String(rtnBytes, "GBK"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return rtnStrBuilder.toString();
    }
}

Related Tutorials