`
r2100
  • 浏览: 30219 次
  • 来自: ...
社区版块
存档分类
最新评论

JAVA字符集和字符串的编码

阅读更多
先提出问题:

都知道,windows XP 的默认编码方式是GBK,

验证如下:

Charset defaultCharset=java.nio.charset.Charset.defaultCharset();

String name=defaultCharset.name();//输入GBK

也可以从另一个编码的角度来验证:

String testStr = "中国";

byte[] bytes = testStr.getBytes(); //[-42, -48, -71, -6]

byte[] gbkbytes = testStr.getBytes("GBK"); //[-42, -48, -71, -6]

是相同的!

这样,问题就来了,如果我想对字符进行UTF-8格式的编码,怎么做?

下面就讨论这个问题。

JDK本身没有提供对字符串进行编码的接口,所有编码相关的类都位于sun.io.*;和java.nio.charset;中.


其实,有一个私有类被隐藏在JDK中,那就是下面要介绍的对String进行编码、解码的工具类:


java.lang.StringCoding;


它是一个内部类,所有的方法都是默认访问的,一位着只有在lang包中的程序才可见它。


直接把这个类复制来,然后把构造访问值改为public (该类的源码附后)


比如要对一个字符串,进行UTF-8编码

String testStr = "中国";


//转换为char数组

char[] defaultChars = {‘中’,‘国’};


//用UTF-8进行编码(encode)

byte[] utfbytes = StringCoding.encode("UTF-8", defaultChars, 0, defaultChars.length);

//用UTF-8进行解码(decode)

char[] utfChars=StringCoding.decode("UTF-8", utfbytes, 0,utfbytes.length);


//将转换编码后的字符串打印出来

String utfStr=Arrays.toString(utfChars);



附源文件 StringCoding:


/*

* @(#)StringCoding.java 1.13 03/12/19

*

* Copyright 2004 Sun Microsystems, Inc. All rights reserved.

* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.

*/


package java.lang;


import java.io.CharConversionException;

import java.io.UnsupportedEncodingException;

import java.lang.ref.SoftReference;

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

import java.nio.BufferOverflowException;

import java.nio.BufferUnderflowException;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;

import java.nio.charset.CharsetEncoder;

import java.nio.charset.CharacterCodingException;

import java.nio.charset.CoderResult;

import java.nio.charset.CodingErrorAction;

import java.nio.charset.IllegalCharsetNameException;

import java.nio.charset.MalformedInputException;

import java.nio.charset.UnsupportedCharsetException;

import sun.io.ByteToCharConverter;

import sun.io.CharToByteConverter;

import sun.io.Converters;

import sun.misc.MessageUtils;

import sun.nio.cs.HistoricallyNamedCharset;



/**

* Utility class for string encoding and decoding.

*/


class StringCoding {


private StringCoding() { }


/* The cached coders for each thread

*/

private static ThreadLocal decoder = new ThreadLocal();

private static ThreadLocal encoder = new ThreadLocal();


private static boolean warnUnsupportedCharset = true;


private static Object deref(ThreadLocal tl) {

SoftReference sr = (SoftReference)tl.get();

if (sr == null)

return null;

return sr.get();

}


private static void set(ThreadLocal tl, Object ob) {

tl.set(new SoftReference(ob));

}


// Trim the given byte array to the given length

//

private static byte[] trim(byte[] ba, int len) {

if (len == ba.length)

return ba;

byte[] tba = new byte[len];

System.arraycopy(ba, 0, tba, 0, len);

return tba;

}


// Trim the given char array to the given length

//

private static char[] trim(char[] ca, int len) {

if (len == ca.length)

return ca;

char[] tca = new char[len];

System.arraycopy(ca, 0, tca, 0, len);

return tca;

}


private static Charset lookupCharset(String csn) {

if (Charset.isSupported(csn)) {

try {

return Charset.forName(csn);

} catch (UnsupportedCharsetException x) {

throw new Error(x);

}

}

return null;

}


private static void warnUnsupportedCharset(String csn) {

if (warnUnsupportedCharset) {

// Use sun.misc.MessageUtils rather than the Logging API or

// System.err since this method may be called during VM

// initialization before either is available.

MessageUtils.err("WARNING: Default charset " + csn +

" not supported, using ISO-8859-1 instead");

warnUnsupportedCharset = false;

}

}



// -- Decoding --


// Encapsulates either a ByteToCharConverter or a CharsetDecoder

//

private static abstract class StringDecoder {

private final String requestedCharsetName;

protected StringDecoder(String requestedCharsetName) {

this.requestedCharsetName = requestedCharsetName;

}

final String requestedCharsetName() {

return requestedCharsetName;

}

abstract String charsetName();

abstract char[] decode(byte[] ba, int off, int len);

}


// A string decoder based upon a ByteToCharConverter

//

private static class ConverterSD

extends StringDecoder

{

private ByteToCharConverter btc;


private ConverterSD(ByteToCharConverter btc, String rcn) {

super(rcn);

this.btc = btc;

}


String charsetName() {

return btc.getCharacterEncoding();

}


char[] decode(byte[] ba, int off, int len) {

int en = btc.getMaxCharsPerByte() * len;

char[] ca = new char[en];

if (len == 0)

return ca;

btc.reset();

int n = 0;

try {

n = btc.convert(ba, off, off + len, ca, 0, en);

n += btc.flush(ca, btc.nextCharIndex(), en);

} catch (CharConversionException x) {

// Yes, this is what we've always done

n = btc.nextCharIndex();

}

return trim(ca, n);

}


}


// A string decoder based upon a CharsetDecoder

//

private static class CharsetSD

extends StringDecoder

{

private final Charset cs;

private final CharsetDecoder cd;


private CharsetSD(Charset cs, String rcn) {

super(rcn);

this.cs = cs;

this.cd = cs.newDecoder()

.onMalformedInput(CodingErrorAction.REPLACE)

.onUnmappableCharacter(CodingErrorAction.REPLACE);

}


String charsetName() {

if (cs instanceof HistoricallyNamedCharset)

return ((HistoricallyNamedCharset)cs).historicalName();

return cs.name();

}


char[] decode(byte[] ba, int off, int len) {

int en = (int)(cd.maxCharsPerByte() * len);

char[] ca = new char[en];

if (len == 0)

return ca;

cd.reset();

ByteBuffer bb = ByteBuffer.wrap(ba, off, len);

CharBuffer cb = CharBuffer.wrap(ca);

try {

CoderResult cr = cd.decode(bb, cb, true);

if (!cr.isUnderflow())

cr.throwException();

cr = cd.flush(cb);

if (!cr.isUnderflow())

cr.throwException();

} catch (CharacterCodingException x) {

// Substitution is always enabled,

// so this shouldn't happen

throw new Error(x);

}

return trim(ca, cb.position());

}


}


static char[] decode(String charsetName, byte[] ba, int off, int len)

throws UnsupportedEncodingException

{

StringDecoder sd = (StringDecoder)deref(decoder);

String csn = (charsetName == null) ? "ISO-8859-1" : charsetName;

if ((sd == null) || !(csn.equals(sd.requestedCharsetName())

|| csn.equals(sd.charsetName()))) {

sd = null;

try {

Charset cs = lookupCharset(csn);

if (cs != null)

sd = new CharsetSD(cs, csn);

else

sd = null;

} catch (IllegalCharsetNameException x) {

// FALL THROUGH to ByteToCharConverter, for compatibility

}

if (sd == null)

sd = new ConverterSD(ByteToCharConverter.getConverter(csn),

csn);

set(decoder, sd);

}

return sd.decode(ba, off, len);

}


static char[] decode(byte[] ba, int off, int len) {

String csn = Converters.getDefaultEncodingName();

try {

return decode(csn, ba, off, len);

} catch (UnsupportedEncodingException x) {

Converters.resetDefaultEncodingName();

warnUnsupportedCharset(csn);

}

try {

return decode("ISO-8859-1", ba, off, len);

} catch (UnsupportedEncodingException x) {

// If this code is hit during VM initialization, MessageUtils is

// the only way we will be able to get any kind of error message.

MessageUtils.err("ISO-8859-1 charset not available: "

+ x.toString());

// If we can not find ISO-8859-1 (a required encoding) then things

// are seriously wrong with the installation.

System.exit(1);

return null;

}

}




// -- Encoding --


// Encapsulates either a CharToByteConverter or a CharsetEncoder

//

private static abstract class StringEncoder {

private final String requestedCharsetName;

protected StringEncoder(String requestedCharsetName) {

this.requestedCharsetName = requestedCharsetName;

}

final String requestedCharsetName() {

return requestedCharsetName;

}

abstract String charsetName();

abstract byte[] encode(char[] cs, int off, int len);

}


// A string encoder based upon a CharToByteConverter

//

private static class ConverterSE

extends StringEncoder

{

private CharToByteConverter ctb;


private ConverterSE(CharToByteConverter ctb, String rcn) {

super(rcn);

this.ctb = ctb;

}


String charsetName() {

return ctb.getCharacterEncoding();

}


byte[] encode(char[] ca, int off, int len) {

int en = ctb.getMaxBytesPerChar() * len;

byte[] ba = new byte[en];

if (len == 0)

return ba;


ctb.reset();

int n;

try {

n = ctb.convertAny(ca, off, (off + len),

ba, 0, en);

n += ctb.flushAny(ba, ctb.nextByteIndex(), en);

} catch (CharConversionException x) {

throw new Error("Converter malfunction: " +

ctb.getClass().getName(),

x);

}

return trim(ba, n);

}


}


// A string encoder based upon a CharsetEncoder

//

private static class CharsetSE

extends StringEncoder

{

private Charset cs;

private CharsetEncoder ce;


private CharsetSE(Charset cs, String rcn) {

super(rcn);

this.cs = cs;

this.ce = cs.newEncoder()

.onMalformedInput(CodingErrorAction.REPLACE)

.onUnmappableCharacter(CodingErrorAction.REPLACE);

}


String charsetName() {

if (cs instanceof HistoricallyNamedCharset)

return ((HistoricallyNamedCharset)cs).historicalName();

return cs.name();

}


byte[] encode(char[] ca, int off, int len) {

int en = (int)(ce.maxBytesPerChar() * len);

byte[] ba = new byte[en];

if (len == 0)

return ba;


ce.reset();

ByteBuffer bb = ByteBuffer.wrap(ba);

CharBuffer cb = CharBuffer.wrap(ca, off, len);

try {

CoderResult cr = ce.encode(cb, bb, true);

if (!cr.isUnderflow())

cr.throwException();

cr = ce.flush(bb);

if (!cr.isUnderflow())

cr.throwException();

} catch (CharacterCodingException x) {

// Substitution is always enabled,

// so this shouldn't happen

throw new Error(x);

}

return trim(ba, bb.position());

}


}


static byte[] encode(String charsetName, char[] ca, int off, int len)

throws UnsupportedEncodingException

{

StringEncoder se = (StringEncoder)deref(encoder);

String csn = (charsetName == null) ? "ISO-8859-1" : charsetName;

if ((se == null) || !(csn.equals(se.requestedCharsetName())

|| csn.equals(se.charsetName()))) {

se = null;

try {

Charset cs = lookupCharset(csn);

if (cs != null)

se = new CharsetSE(cs, csn);

} catch (IllegalCharsetNameException x) {

// FALL THROUGH to CharToByteConverter, for compatibility

}

if (se == null)

se = new ConverterSE(CharToByteConverter.getConverter(csn),

csn);

set(encoder, se);

}

return se.encode(ca, off, len);

}


static byte[] encode(char[] ca, int off, int len) {

String csn = Converters.getDefaultEncodingName();

try {

return encode(csn, ca, off, len);

} catch (UnsupportedEncodingException x) {

Converters.resetDefaultEncodingName();

warnUnsupportedCharset(csn);

}

try {

return encode("ISO-8859-1", ca, off, len);

} catch (UnsupportedEncodingException x) {

// If this code is hit during VM initialization, MessageUtils is

// the only way we will be able to get any kind of error message.

MessageUtils.err("ISO-8859-1 charset not available: "

+ x.toString());

// If we can not find ISO-8859-1 (a required encoding) then things

// are seriously wrong with the installation.

System.exit(1);

return null;

}

}


}
分享到:
评论

相关推荐

    java字符串的各种编码转换

    根据提供的文件信息,本文将详细解释Java中字符串的不同编码转换方法及原理,并深入探讨每种编码格式的特点。 ### Java字符串的编码转换 在Java中,处理不同字符集之间的字符串转换是一项常见任务。尤其是在处理...

    java字符集编码问题

    ### Java字符集编码问题详解 #### 一、引言 在Java编程中,字符集编码问题是一个常见且重要的议题。由于不同的系统、平台以及网络环境中可能存在多种字符编码格式,这导致了在处理文本数据时可能会遇到编码不一致...

    java字符串编码转换

    ### Java字符串编码转换详解 #### 一、Java 字符串编码转换基础 在Java中,字符串的处理是非常常见的操作之一,而字符编码是确保数据正确显示的关键因素。本篇文章将重点介绍Java中字符串编码的转换方法及其在Web...

    JAVA及相关字符集编码问题

    在JAVA开发中,正确处理字符集编码至关重要,以避免乱码和数据不一致的问题。 一、ISO8859-1与ASCII ISO8859-1是一种单字节编码标准,通常用于西欧语言,其编码范围为0-255。在ISO8859-1中,ASCII字符集是其子集,...

    Java 所有字符串转UTF-8 万能工具类-GetEncode.java

    不需要关心接受的字符串编码是UTF_8还是GBK,还是ios-8859-1,自动转换为utf-8编码格式,无需判断字符串原有编码,用法://处理编码String newStr = GetEncode.transcode(oldStr);

    java 字符串中文判断

    总的来说,通过理解Unicode编码和Java的字符处理机制,我们可以有效地处理中文字符。在实际项目中,这样的工具类对于处理中文字符的检测和统计是非常有用的,能够提高代码的可读性和复用性。在Java中处理字符串,...

    java 字符串转16进制Ascii

    在Java编程语言中,将字符串转换为16进制ASCII值是一个常见的操作,尤其是在处理数据编码、网络通信或存储时。这个过程涉及到字符到数字的...理解这些概念和方法,对于在Java开发过程中处理字符串编码问题至关重要。

    java字符集

    ### Java字符集详解 #### 一、概述与背景 本文主要探讨了字符编码的基本概念以及Java编程语言如何处理不同字符集。随着信息技术的发展,字符编码技术也在不断演进,以支持全球范围内各种语言的文本表示需求。文章...

    字符编码和字符集研究

    字符编码和字符集是计算机处理文字和符号的基础。字符集是指一组特定的字符集合,它包含文字、符号、数字等元素。例如,英文字符集包含了所有的英文字母和符号,而汉字字符集则包含了所有汉字。字符集可以是某个语言...

    Java中的字符集编码入门(二)编码字符集与字符集编码的区别[参考].pdf

    总的来说,字符集编码和字符集编码是文本处理中的核心概念,理解它们的区别有助于我们在编程中有效地处理字符和文本数据。无论是开发Web应用、桌面软件还是移动应用,都需要对字符编码有深入的理解,以便在处理各种...

    JAVA 字符串应用笔记

    以上内容是基于"JAVA 字符串应用笔记"可能涵盖的基本知识点,对于初学者来说,理解和掌握这些概念是进阶学习Java和Android开发的基础。在实际开发中,还会涉及到更多高级特性和实践技巧,如字符串格式化、正则表达式...

    JAVA字符串操作类CTool.java字符转换类.rar

    字符串从GBK编码转换为Unicode编码、对字符串进行md5加密、sql语句 处理、把null转换为字符串"0"、null 处理、long型变量转换成String型变量、int型变量转换成String型变量、String型变量转换成int型变量、把null值...

    Java Unicode 和字符集

    在Java中,字符串是以Unicode的形式存储的,这意味着Java的String类内部使用UTF-16编码来表示字符。Java通过使用`char`类型来表示单个Unicode字符,该类型占用16位,足够表示基本多文种平面上的所有字符。对于超出...

    Java中字符集的详细介绍

    当使用`String.getBytes()`方法时,如果没有指定编码,Java会默认使用本地字符集,通常是GBK或ASCII。例如,对于英文字符串`s1 = "cn"`,其长度为2,因为ASCII中每个英文字符是一个字节。而中文字符串`s2 = "中国"`...

    java_字符编码 Javajava_字符编码问题

    - 在进行字符编码转换时,必须明确指定源编码和目标编码。 - 如果不清楚数据的原始编码,可能会导致乱码问题。 - 在处理多语言或多编码环境时,应尽可能统一使用一种编码(如 UTF-8)以减少转换过程中的问题。 ####...

    JAVA字符集

    例如,`getBytes(charset)`方法会根据指定的字符集将字符串编码成字节数组,而`new String(byte[], charset)`则是将字节数组解码为字符串。 在处理编码问题时,Java提供了一些关键的类和接口,如`Charset`、`...

    java与c交互传递字符串和整型

    在JNI中,我们使用`NewStringUTF`函数从Java字符串创建一个C的UTF-8编码的字符串,然后使用`GetStringUTFChars`获取其实际内容。在C中处理完字符串后,需要使用`ReleaseStringUTFChars`释放资源。这个过程确保了内存...

    java使用URLDecoder和URLEncoder对中文字符进行编码和解码

    这两个类位于`java.net`包下,可以帮助开发者进行字符串编码和解码,确保数据在网络传输过程中的正确性。 `URLEncoder`类提供了`encode`静态方法,用于将普通字符串编码成`application/x-www-form-urlencoded` MIME...

    如何用java实现不同编码方式字符串的转换(包含异常处理、重复不终止输入、缓冲区bufferedreader的使用)

    在进行字符串转换时,确保正确识别源字符串的编码和目标编码是关键,否则可能会导致乱码。 Java中的`Charset`类提供了处理字符编码的方法。例如,我们可以使用`new String(byte[], charsetName)`构造函数将字节数组...

Global site tag (gtag.js) - Google Analytics