zoukankan      html  css  js  c++  java
  • Java 输出指定编码的字符串

    Java Sting类有个根据byte,字符编码来输出的构造函数。
    以下为java文档中的解释。

    public String(byte[] bytes, String charsetName) throws UnsupportedEncodingException
    Constructs a new String by decoding the specified array of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.

    The behavior of this constructor when the given bytes are not valid in the given charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

    Parameters:
    bytes - the bytes to be decoded into characters
    charsetName - the name of a supported charset
    Throws:
    UnsupportedEncodingException - If the named charset is not supported
    Since:
    JDK1.1

    下面代码为转换的函数:

     1 /***
     2  * 按照指定编码转换字符串
     3  * @param str 需要转换的字符串
     4  * @param srcEncode 传递过来的字符串编码格式
     5  * @param dstEncode 需要转换成的编码格式
     6  * @return 指定编码格式的字符串
     7  */
     8 public String translate(String str, String srcEncode,String dstEncode) {
     9     String tempStr = "";
    10     try {
    11         tempStr = new String(str.getBytes(srcEncode),dstEncode);
    12     } catch (UnsupportedEncodingException e) {
    13         // TODO Auto-generated catch block
    14         e.printStackTrace();
    15     }
    16     return tempStr;
    17 }
  • 相关阅读:
    三层架构之解耦
    自动升级 组件
    C语言常量与指针
    ASP.NET MVC Model元数据
    Web层后端权限模块
    java中文排序问题(转)
    JDWP
    bat执行java程序的脚本解析
    jdom dom4j解析xml不对dtd doctype进行验证(转)
    Dom4j SAXReader Constructors
  • 原文地址:https://www.cnblogs.com/tianyaxue/p/3145099.html
Copyright © 2011-2022 走看看