[JAVA] Create your own encode for String.getBytes ()

Create your own encode for String.getBytes ()

--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()) {


		//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
		//Illegal input
		if(result.isMalformed()) {
			//This is basically rare.

	//Flash to encoding result buffer

	//Flip the buffer(Invert)Return to start position

	return Arrays.copyOf(outBuf.array(), outBuf.limit());

Recommended Posts

Create your own encode for String.getBytes ()
Create your own Android app for Java learning
Create your own Java annotations
Create your own Solr Function Query
Create your own validator with Bean Validation
Utilization of Talend component (5) Create your own component
Create your own Utility with Thymeleaf with Spring Boot
[Introduction to Java Data Structures] Create your own fast ArrayDeque for primitive types
Make your own pomodoro
Create a base for your batch processing project in Eclipse.
Make your own Rails validate
Create advanced functions for Yellowfin
Make your own Elasticsearch plugin
How to create your own Controller corresponding to / error with Spring Boot