--The character code of the opponent system is SJIS, and it was necessary to send the characters that are garbled at the Unicode code point. --It is judged that it is faster to replace at the time of encoding than to replace twice.
private static final Map<Character, byte[]> conversionCharsetMap = new LinkedHashMap<Character, byte[]>(){
{
put('~', new byte[]{(byte) 0x81, (byte) 0x60});
put('-', new byte[]{(byte) 0x81, (byte) 0x7C});
put('¢', new byte[]{(byte) 0x81, (byte) 0x91});
put('£', new byte[]{(byte) 0x81, (byte) 0x92});
put('¬', new byte[]{(byte) 0x81, (byte) 0xCA});
put('―', new byte[]{(byte) 0x81, (byte) 0x5C});
put('∥', new byte[]{(byte) 0x81, (byte) 0x61});
}
};
public byte[] encode(String str, String charsetName){
Charset charset = Charset.forName(charsetName);
CharsetEncoder encoder = charset.newEncoder();
CharBuffer inBuf = CharBuffer.wrap(str);
ByteBuffer outBuf = ByteBuffer.allocate(inBuf.length() * (int)encoder.maxBytesPerChar());
CoderResult result;
//Loop while CoderResult returns an error
while((result = encoder.encode(inBuf, outBuf, true)).isError()) {
//reset
encoder.reset();
//If mapping is not possible
//For example, TF-8⇒SJIS(Not MS932)Characters that fail in ~ ∥-¢£¬― etc. Enter here
if(result.isUnmappable()) {
//Get 1 character (character that failed to map)
char ch = inBuf.get();
byte[] val = null;
//Put the processing of what to do if mapping fails in this area
//Here, the bytecode for SJIS of the character that failed to be mapped is obtained from the map.
val = conversionCharsetMap.get(ch);
//Put to byte buffer for encoding result
outBuf.put(val);
}
//Illegal input
if(result.isMalformed()) {
//This is basically rare.
}
}
//Flash to encoding result buffer
encoder.flush(outBuf);
//Flip the buffer(Invert)Return to start position
outBuf.flip();
return Arrays.copyOf(outBuf.array(), outBuf.limit());
}
Recommended Posts