首先說明這里指的是Java中的String,雖然我已經決定轉戰C/C++了,但是因為今天碰到一個問題,還是來看一下。String的定義如下:
public final class String
{
private final char value[]; // 保存的字符串
private final int offset; // 開始的位置
private final int count; // 字符數目
private int hash; // 緩存的hash值
......
}
在Debug的時候可以看到保存的值如下:
需要說明一下的是:如果沒有調用過hashCode(),那么hash的值為0。容易知道這里的value也就是真正保存的字符串的值(也就是“字符串測試”)的char數組,而每個char的值是多少呢?很容易驗證:Unicode。
到這里大家也就猜到我們常用的subString是怎么實現的了:如果是讓我們實現的話讓new String使用相同的value(char數組),只修改offset和count就可以了。這樣的話既省空間又快(不需要拷貝),而事實上也是這樣的:
public String substring(int beginIndex) {
return substring(beginIndex, count);
}
public String substring(int beginIndex, int endIndex) {
......
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
既然是在討論字符串,JVM默認使用的是什么編碼呢?通過調試可以發現:
public static Charset defaultCharset() {
if (defaultCharset == null) {
synchronized (Charset.class) {
java.security.PrivilegedAction pa = new GetPropertyAction("file.encoding");
String csn = (String)AccessController.doPrivileged(pa);
Charset cs = lookup(csn);
if (cs != null)
defaultCharset = cs;
else
defaultCharset = forName("UTF-8");
}
}
其中defaultCharset的值可以通過:
-Dfile.encoding=utf-8
進行設置。當然如果你想設置為“abc”也可以,但會默認設置為UTF-8??梢酝ㄟ^System.getProperty("file.encoding")來看具體的值??磀efaultCharset是為什么呢?因為網絡傳輸的過程中應該都是byte數組,不同的編碼方式得到的byte數組可能是不相同的。所以,我們得知道編碼方式是怎么得到的吧?具體得到byte數組的方法也就是我們下面重點要看的getBytes了,它最終要調用的是CharsetEncoder的encode方法,如下:
public final CoderResult encode(CharBuffer in, ByteBuffer out, boolean endOfInput) {
int newState = endOfInput ? ST_END : ST_CODING;
if ((state != ST_RESET) && (state != ST_CODING) && !(endOfInput && (state == ST_END)))
throwIllegalStateException(state, newState);
state = newState;
for (;;) {
CoderResult cr;
try {
cr = encodeLoop(in, out);
} catch (BufferUnderflowException x) {
throw new CoderMalfunctionError(x);
} catch (BufferOverflowException x) {
throw new CoderMalfunctionError(x);
}
if (cr.isOverflow())
return cr;
if (cr.isUnderflow()) {
if (endOfInput && in.hasRemaining()) {
cr = CoderResult.malformedForLength(in.remaining());
} else {
return cr;
}
}
CodingErrorAction action = null;
if (cr.isMalformed())
action = malformedInputAction;
else if (cr.isUnmappable())
action = unmappableCharacterAction;
else
assert false : cr.toString();
if (action == CodingErrorAction.REPORT)
return cr;
if (action == CodingErrorAction.REPLACE) {
if (out.remaining() < replacement.length)
return CoderResult.OVERFLOW;
out.put(replacement);
}
if ((action == CodingErrorAction.IGNORE) || (action == CodingErrorAction.REPLACE)) {
in.position(in.position() + cr.length());
continue;
}
assert false;
}
}
當然首先會根據需要的編碼格式選擇對應的CharsetEncoder,而最主要的是不同的CharsetEncoder實現了不同的encodeLoop方法。這里可能會不明白為什么這里有個for(;;)?其實看CharsetEncoder所處的包(nio)和它的參數也就大概明白了:這個函數是可以處理流的(雖然我們這里使用的時候不會循環)。
在encodeLoop方法中會將盡可能多的char轉換為byte,new String差不多就是上面的逆過程。
在實際的開發過程中經常會遇到亂碼問題:
在上傳文件的時候取到文件名;
JS傳到后端的字符串;
首先先嘗試下下面代碼的的運行結果: