change String Charset - Java java.lang

Java examples for java.lang:String Unicode

Description

change String Charset

Demo Code


import java.io.UnsupportedEncodingException;

public class Main{
    public static void main(String[] argv){
        String str = "java2s.com";
        String newCharset = "UTF-8";
        System.out.println(changeCharset(str,newCharset));
    }//from  w w  w  . j  ava 2  s. co  m
    
    public static String changeCharset(String str, String oldCharset,
            String newCharset) {
        try {
            if (str != null) {
                byte[] bs = str.getBytes(oldCharset);

                return new String(bs, newCharset);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }
    
    public static String changeCharset(String str, String newCharset) {
        try {
            if (str != null) {
                byte[] bs = str.getBytes();
                return new String(bs, newCharset);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }
}

Related Tutorials