Java Code Examples for java.nio.charset.CharsetDecoder

Following code examples demonstrate how to use java.nio.charset.CharsetDecoderfrom java. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use java.nio.charset.CharsetDecoderand various code implementation of this class.

    public void testInvalidDecoding() throws IOException {

        byte[][] invalidSequences = new byte[][] {
            { (byte) 0xC0, (byte) 0x80 },
            { (byte) 0xC0, (byte) 0xC1 },
            { (byte) 0x2F, (byte) 0xC0, (byte) 0xAE, (byte) 0x2E, (byte) 0x2F },
            { (byte) 0xF8 },
            { (byte) 0x80 }
        };

        CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
        decoder.onMalformedInput(CodingErrorAction.REPORT);

        
        for (byte[] bytes : invalidSequences) {
            try {
                decoder.decode(ByteBuffer.wrap(bytes));
                fail("No exception thrown on " + Arrays.toString(bytes));
            } catch (MalformedInputException e) {
            }
        }

        
        for (byte[] bytes : invalidSequences) {
            try {
                ByteBuffer bb = ByteBuffer.allocateDirect(8);
                bb.put(bytes).flip();
                decoder.decode(bb);
                fail("No exception thrown on " + Arrays.toString(bytes));
            } catch (MalformedInputException e) {
            }
        }
    } 


	public void test_decode() throws CharacterCodingException {

		
		CharsetDecoder decoder2 = Charset.forName("UTF-16").newDecoder();
		decoder2.onMalformedInput(CodingErrorAction.REPORT);
		decoder2.onUnmappableCharacter(CodingErrorAction.REPORT);
		ByteBuffer in = ByteBuffer.wrap(new byte[] { 109, 97, 109 });
		try {
			decoder2.decode(in);
			fail("Assert 3: MalformedInputException should have thrown");
		} catch (MalformedInputException e) {
		} 
	} 

    public void testInvalidDecoding() throws IOException {

        byte[][] invalidSequences = new byte[][] {
            { (byte) 0xC0, (byte) 0x80 },
            { (byte) 0xC0, (byte) 0xC1 },
            { (byte) 0x2F, (byte) 0xC0, (byte) 0xAE, (byte) 0x2E, (byte) 0x2F },
            { (byte) 0xF8 },
            { (byte) 0x80 }
        };

        CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
        decoder.onMalformedInput(CodingErrorAction.REPORT);
        decoder.onUnmappableCharacter(CodingErrorAction.REPORT);

        
        for (byte[] bytes : invalidSequences) {
            try {
                CharBuffer cb = decoder.decode(ByteBuffer.wrap(bytes));
                fail("No exception thrown on " + Arrays.toString(bytes) + " '" + cb + "'");
            } catch (MalformedInputException expected) {
            }
        }

        
        for (byte[] bytes : invalidSequences) {
            try {
                ByteBuffer bb = ByteBuffer.allocateDirect(8);
                bb.put(bytes).flip();
                CharBuffer cb = decoder.decode(bb);
                fail("No exception thrown on " + Arrays.toString(bytes) + " '" + cb + "'");
            } catch (MalformedInputException expected) {
            }
        }
    } 

	public void test_decode() throws CharacterCodingException {


		CharsetDecoder decoder2 = Charset.forName("UTF-16").newDecoder();
		decoder2.onMalformedInput(CodingErrorAction.REPORT);
		decoder2.onUnmappableCharacter(CodingErrorAction.REPORT);
		ByteBuffer in = ByteBuffer.wrap(new byte[] { 109, 97, 109 });
		try {
			decoder2.decode(in);
			fail("Assert 3: MalformedInputException should have thrown");
		} catch (MalformedInputException e) {
		}
	} 

	public final CharsetDecoder reset() {
		pending.clear();
		return backing.reset();
	} 

    @Test
    public default void verifyGenericType()
    throws Exception {
        final Class<SUT> sut = createNewSUT();
        assertTrue("This j8unit test interface is used with a generic type that is illegaly not assignable to CharsetDecoder.class!",
                   CharsetDecoder.class.isAssignableFrom(sut));
    } 

Advertisement
Javadoc
An engine that can transform a sequence of bytes in a specific charset into a sequence of sixteen-bi

t Unicode characters.

The input byte sequence is provided in a byte buffer or a series of such buffers. The output character sequence is written to a character buffer or a series of such buffers. A decoder should always be used by making the following sequence of method invocations, hereinafter referred to as a decoding operation:

Reset the decoder via the #reset reset method, unless it has not been used before;

Invoke the #decode decode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;

Invoke the #decode decode method one final time, passing true for the endOfInput argument; and then

Invoke the #flush flush method so that the decoder can flush any internal state to the output buffer. Each invocation of the #decode decode method will decode as many bytes as possible from the input buffer, writing the resulting characters to the output buffer. The #decode decode method returns when more input is required, when there is not enough room in the output buffer, or when a decoding error has occurred. In each case a CoderResult object is returned to describe the reason for termination. An invoker can examine this object and fill the input buffer, flush the output buffer, or attempt to recover from a decoding error, as appropriate, and try again.

There are two general types of decoding errors. If the input byte sequence is not legal for this charset then the input is considered malformed. If the input byte sequence is legal but cannot be mapped to a valid Unicode character then an unmappable character has been encountered.

How a decoding error is handled depends upon the action requested for that type of error, which is described by an instance of the {@linkplain CodingErrorAction class. The possible error actions are to {@linkplain CodingErrorAction#IGNORE ignore the erroneous input, CodingErrorAction#REPORT report the error to the invoker via the returned CoderResult object, or {@linkplain CodingErrorAction#REPLACE replace the erroneous input with the current value of the replacement string. The replacement has the initial value "\uFFFD"; its value may be changed via the #replaceWith(java.lang.String) replaceWith method.

The default action for malformed-input and unmappable-character errors is to {@linkplain CodingErrorAction#REPORT report them. The malformed-input error action may be changed via the #onMalformedInput(CodingErrorAction) onMalformedInput method; the unmappable-character action may be changed via the #onUnmappableCharacter(CodingErrorAction) onUnmappableCharacter method.

This class is designed to handle many of the details of the decoding process, including the implementation of error actions. A decoder for a specific charset, which is a concrete subclass of this class, need only implement the abstract #decodeLoop decodeLoop method, which encapsulates the basic decoding loop. A subclass that maintains internal state should, additionally, override the #implFlush implFlush and #implReset implReset methods.

Instances of this class are not safe for use by multiple concurrent threads. @author Mark Reinhold @author JSR-51 Expert Group @since 1.4 @see ByteBuffer @see CharBuffer @see Charset @see CharsetEncoder

Read More
Advertisement