當前位置: 首頁>>代碼示例>>Java>>正文


Java Charset.newDecoder方法代碼示例

本文整理匯總了Java中java.nio.charset.Charset.newDecoder方法的典型用法代碼示例。如果您正苦於以下問題:Java Charset.newDecoder方法的具體用法?Java Charset.newDecoder怎麽用?Java Charset.newDecoder使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.nio.charset.Charset的用法示例。


在下文中一共展示了Charset.newDecoder方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: B2CConverter

import java.nio.charset.Charset; //導入方法依賴的package包/類
public B2CConverter(String encoding, boolean replaceOnError)
        throws IOException {
    byte[] left = new byte[LEFTOVER_SIZE];
    leftovers = ByteBuffer.wrap(left);
    CodingErrorAction action;
    if (replaceOnError) {
        action = CodingErrorAction.REPLACE;
    } else {
        action = CodingErrorAction.REPORT;
    }
    Charset charset = getCharset(encoding);
    // Special case. Use the Apache Harmony based UTF-8 decoder because it
    // - a) rejects invalid sequences that the JVM decoder does not
    // - b) fails faster for some invalid sequences
    if (charset.equals(UTF_8)) {
        decoder = new Utf8Decoder();
    } else {
        decoder = charset.newDecoder();
    }
    decoder.onMalformedInput(action);
    decoder.onUnmappableCharacter(action);
}
 
開發者ID:sunmingshuai,項目名稱:apache-tomcat-7.0.73-with-comment,代碼行數:23,代碼來源:B2CConverter.java

示例2: getConverter

import java.nio.charset.Charset; //導入方法依賴的package包/類
/**
 * Utility method to find a CharsetDecoder in the
 * cache or create a new one if necessary.  Throws an
 * INTERNAL if the code set is unknown.
 */
protected CharsetDecoder getConverter(String javaCodeSetName) {

    CharsetDecoder result = null;
    try {
        result = cache.getByteToCharConverter(javaCodeSetName);

        if (result == null) {
            Charset tmpCharset = Charset.forName(javaCodeSetName);
            result = tmpCharset.newDecoder();
            cache.setConverter(javaCodeSetName, result);
        }

    } catch(IllegalCharsetNameException icne) {
        // This can only happen if one of our charset entries has
        // an illegal name.
        throw wrapper.invalidBtcConverterName( icne, javaCodeSetName ) ;
    }

    return result;
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:26,代碼來源:CodeSetConversion.java

示例3: for

import java.nio.charset.Charset; //導入方法依賴的package包/類
@Test
public void testCharAt$1_byte() {
    System.out.println("testCharAt$1_byte");
    int index = 0;       
    Charset cs = Charset.forName(UTF_8);
    for(TypeOfStream stype: TypeOfStream.values()) {
        try {
            InputStream stream = getInputStream(stype, TypeOfContent.BYTE_1, cs);
            BufferedCharSequence instance = new BufferedCharSequence(stream, cs.newDecoder(), 1);
            char expResult = 'a';
            char result = instance.charAt(index);
            assertEquals(expResult, result);

        } catch (IndexOutOfBoundsException ioobe) {
            ioobe.printStackTrace();
            fail(ioobe.toString());
        } catch (BufferedCharSequence.SourceIOException bcse) {
            bcse.printStackTrace();
            fail(bcse.toString());
        }
    }
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:23,代碼來源:BufferedCharSequenceTest.java

示例4: getFile

import java.nio.charset.Charset; //導入方法依賴的package包/類
@Test
 public void testCharAt$10_byte() {
     System.out.println("testCharAt$10_byte");
     File file = getFile("10_bytes");
     Charset cs = Charset.forName(UTF_8);
     for(TypeOfStream stype: TypeOfStream.values()) {
         InputStream stream = getInputStream(stype, TypeOfContent.BYTE_10, cs);
         BufferedCharSequence instance = new BufferedCharSequence(stream, cs.newDecoder(), 10);
         instance.setMaxBufferSize(10);
         char result;

         result = instance.charAt(0);
         assertEquals('0', result);

         result = instance.charAt(9);
         assertEquals('9', result);

         result = instance.charAt(5);
         assertEquals('5', result);

         result = instance.charAt(9);
         assertEquals('9', result);
     }
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:25,代碼來源:BufferedCharSequenceTest.java

示例5: decodeISOChar

import java.nio.charset.Charset; //導入方法依賴的package包/類
/**
 * Decode ISO encoded character
 *
 * @param isoBytes Bytes representing the char
 * @return String representing the encoded char
 */
public static String decodeISOChar(byte[] isoBytes) {

    /* Return the Entity value if decode fails */
    String decodedChar = String.valueOf("&" + (int) isoBytes[0] + ";");

    /* Only decode if Charset ISO-8859-1 is available */
    if (Charset.isSupported("ISO-8859-1")) {
        Charset isoCharset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = isoCharset.newDecoder();

        ByteBuffer isoBytesRef = ByteBuffer.wrap(isoBytes);
        CharBuffer decodedCharBuf = null;
        try {
            decodedCharBuf = decoder.decode(isoBytesRef);
        } catch (CharacterCodingException e) {
            GUI.logger.info("decodeChar() " + e.toString());
        }
        return String.valueOf(decodedCharBuf);
    }
    return decodedChar;
}
 
開發者ID:openaudible,項目名稱:openaudible,代碼行數:28,代碼來源:StringShop.java

示例6: B2CConverter

import java.nio.charset.Charset; //導入方法依賴的package包/類
public B2CConverter(String encoding, boolean replaceOnError) throws IOException {
	byte[] left = new byte[LEFTOVER_SIZE];
	leftovers = ByteBuffer.wrap(left);
	CodingErrorAction action;
	if (replaceOnError) {
		action = CodingErrorAction.REPLACE;
	} else {
		action = CodingErrorAction.REPORT;
	}
	Charset charset = getCharset(encoding);
	// Special case. Use the Apache Harmony based UTF-8 decoder because it
	// - a) rejects invalid sequences that the JVM decoder does not
	// - b) fails faster for some invalid sequences
	if (charset.equals(UTF_8)) {
		decoder = new Utf8Decoder();
	} else {
		decoder = charset.newDecoder();
	}
	decoder.onMalformedInput(action);
	decoder.onUnmappableCharacter(action);
}
 
開發者ID:how2j,項目名稱:lazycat,代碼行數:22,代碼來源:B2CConverter.java

示例7: main

import java.nio.charset.Charset; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception, AlluxioException {
	// 1.創建鍵值對係統實例
	KeyValueSystem kvs = KeyValueSystem.Factory.create();

	// 2.開啟鍵值對reader
	KeyValueStoreReader reader = kvs.openStore(new AlluxioURI("/alluxiotest/kvstore"));

	// 3.通過迭代器遍曆存儲中的鍵值對
	// 3.1創建解碼器
	Charset charset = Charset.forName("UTF-8");
	CharsetDecoder decoder = charset.newDecoder();

	// 3.2遍曆並解碼
	KeyValueIterator iterator = reader.iterator();
	while (iterator.hasNext()) {
		KeyValuePair pair = iterator.next();
		String key = decoder.decode(pair.getKey().asReadOnlyBuffer()).toString();
		String value = decoder.decode(pair.getValue().asReadOnlyBuffer()).toString();
		System.out.println("key=" + key + ",value=" + value);
	}
	// 4.關閉鍵值對reader
	reader.close();
}
 
開發者ID:zhangjunfang,項目名稱:alluxio,代碼行數:24,代碼來源:KeyValueReader002.java

示例8: testCharAt_File

import java.nio.charset.Charset; //導入方法依賴的package包/類
/**
 * Test of charAt method, of class BufferedCharSequence.
 */
@Test(expected=IndexOutOfBoundsException.class)
public void testCharAt_File() {
    System.out.println("charAt_File");
    int index = 0;        
    Charset cs = Charset.forName(UTF_8);
    InputStream stream = getInputStream(TypeOfStream.FILE, TypeOfContent.BYTE_0, cs);
    BufferedCharSequence instance = new BufferedCharSequence(stream, cs.newDecoder(), 0);
    instance.charAt(index);
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:13,代碼來源:BufferedCharSequenceTest.java

示例9: test

import java.nio.charset.Charset; //導入方法依賴的package包/類
static void test(String expectedCharset, byte[] input) throws Exception {
    Charset cs = Charset.forName("x-JISAutoDetect");
    CharsetDecoder autoDetect = cs.newDecoder();

    Charset cs2 = Charset.forName(expectedCharset);
    CharsetDecoder decoder = cs2.newDecoder();

    ByteBuffer bb = ByteBuffer.allocate(128);
    CharBuffer charOutput = CharBuffer.allocate(128);
    CharBuffer charExpected = CharBuffer.allocate(128);

    bb.put(input);
    bb.flip();
    bb.mark();

    CoderResult result = autoDetect.decode(bb, charOutput, true);
    checkCoderResult(result);
    charOutput.flip();
    String actual = charOutput.toString();

    bb.reset();

    result = decoder.decode(bb, charExpected, true);
    checkCoderResult(result);
    charExpected.flip();
    String expected = charExpected.toString();

    check(actual.equals(expected),
          String.format("actual=%s expected=%s", actual, expected));
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:31,代碼來源:NIOJISAutoDetectTest.java

示例10: decode

import java.nio.charset.Charset; //導入方法依賴的package包/類
static Result decode(Charset cs, byte[] ba, int off, int len) {
    // (1)We never cache the "external" cs, the only benefit of creating
    // an additional StringDe/Encoder object to wrap it is to share the
    // de/encode() method. These SD/E objects are short-lived, the young-gen
    // gc should be able to take care of them well. But the best approach
    // is still not to generate them if not really necessary.
    // (2)The defensive copy of the input byte/char[] has a big performance
    // impact, as well as the outgoing result byte/char[]. Need to do the
    // optimization check of (sm==null && classLoader0==null) for both.
    // (3)There might be a timing gap in isTrusted setting. getClassLoader0()
    // is only checked (and then isTrusted gets set) when (SM==null). It is
    // possible that the SM==null for now but then SM is NOT null later
    // when safeTrim() is invoked...the "safe" way to do is to redundant
    // check (... && (isTrusted || SM == null || getClassLoader0())) in trim
    // but it then can be argued that the SM is null when the operation
    // is started...
    if (cs == UTF_8) {
        return StringDecoderUTF8.decode(ba, off, len, new Result());
    }
    CharsetDecoder cd = cs.newDecoder();
    // ascii fastpath
    if (cs == ISO_8859_1 || ((cd instanceof ArrayDecoder) &&
                             ((ArrayDecoder)cd).isASCIICompatible() &&
                             !hasNegatives(ba, off, len))) {
         if (COMPACT_STRINGS) {
             return new Result().with(Arrays.copyOfRange(ba, off, off + len),
                                      LATIN1);
         } else {
             return new Result().with(StringLatin1.inflate(ba, off, len), UTF16);
         }
    }
    int en = scale(len, cd.maxCharsPerByte());
    if (len == 0) {
        return new Result().with();
    }
    if (cs.getClass().getClassLoader0() != null &&
        System.getSecurityManager() != null) {
        ba =  Arrays.copyOfRange(ba, off, off + len);
        off = 0;
    }
    cd.onMalformedInput(CodingErrorAction.REPLACE)
      .onUnmappableCharacter(CodingErrorAction.REPLACE)
      .reset();

    char[] ca = new char[en];
    if (cd instanceof ArrayDecoder) {
        int clen = ((ArrayDecoder)cd).decode(ba, off, len, ca);
        return new Result().with(ca, 0, clen);
    }
    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 new Result().with(ca, 0, cb.position());
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:66,代碼來源:StringCoding.java

示例11: decodeLoop

import java.nio.charset.Charset; //導入方法依賴的package包/類
private CoderResult decodeLoop(Charset cs,
                               ByteBuffer src, CharBuffer dst) {
    detectedDecoder = (DelegatableDecoder) cs.newDecoder();
    return detectedDecoder.decodeLoop(src, dst);
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:6,代碼來源:JISAutoDetect.java

示例12: DefaultBinaryContext

import java.nio.charset.Charset; //導入方法依賴的package包/類
public DefaultBinaryContext ( final Charset charset, final Interner<String> stringInterner )
{
    this.encoder = charset.newEncoder ();
    this.decoder = charset.newDecoder ();
    this.stringInterner = stringInterner == null ? InternerHelper.makeNoOpInterner () : stringInterner;
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:7,代碼來源:DefaultBinaryContext.java

示例13: decodeLoop

import java.nio.charset.Charset; //導入方法依賴的package包/類
protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) {
    if (detectedDecoder == null) {
        copyLeadingASCII(src, dst);

        // All ASCII?
        if (! src.hasRemaining())
            return CoderResult.UNDERFLOW;
        // Overflow only if there is still ascii but no out buffer.
        if (!dst.hasRemaining() &&
            isPlainASCII(src.get(src.position())))
            return CoderResult.OVERFLOW;

        // We need to perform double, not float, arithmetic; otherwise
        // we lose low order bits when src is larger than 2**24.
        int cbufsiz = (int)(src.limit() * (double)maxCharsPerByte());
        CharBuffer sandbox = CharBuffer.allocate(cbufsiz);

        // First try ISO-2022-JP, since there is no ambiguity
        Charset cs2022 = Charset.forName("ISO-2022-JP");
        DelegatableDecoder dd2022
            = (DelegatableDecoder) cs2022.newDecoder();
        ByteBuffer src2022 = src.asReadOnlyBuffer();
        CoderResult res2022 = dd2022.decodeLoop(src2022, sandbox);
        if (! res2022.isError())
            return decodeLoop(dd2022, src, dst);

        // We must choose between EUC and SJIS
        Charset csEUCJ = Charset.forName(EUCJPName);
        Charset csSJIS = Charset.forName(SJISName);

        DelegatableDecoder ddEUCJ
            = (DelegatableDecoder) csEUCJ.newDecoder();
        DelegatableDecoder ddSJIS
            = (DelegatableDecoder) csSJIS.newDecoder();

        ByteBuffer srcEUCJ = src.asReadOnlyBuffer();
        sandbox.clear();
        CoderResult resEUCJ = ddEUCJ.decodeLoop(srcEUCJ, sandbox);
        // If EUC decoding fails, must be SJIS
        if (resEUCJ.isError())
            return decodeLoop(ddSJIS, src, dst);
        ByteBuffer srcSJIS = src.asReadOnlyBuffer();
        CharBuffer sandboxSJIS = CharBuffer.allocate(cbufsiz);
        CoderResult resSJIS = ddSJIS.decodeLoop(srcSJIS, sandboxSJIS);
        // If SJIS decoding fails, must be EUC
        if (resSJIS.isError())
            return decodeLoop(ddEUCJ, src, dst);

        // From here on, we have some ambiguity, and must guess.

        // We prefer input that does not appear to end mid-character.
        if (srcEUCJ.position() > srcSJIS.position())
            return decodeLoop(ddEUCJ, src, dst);

        if (srcEUCJ.position() < srcSJIS.position())
            return decodeLoop(ddSJIS, src, dst);

        // end-of-input is after the first byte of the first char?
        if (src.position() == srcEUCJ.position())
            return CoderResult.UNDERFLOW;

        // Use heuristic knowledge of typical Japanese text
        sandbox.flip();
        return decodeLoop(looksLikeJapanese(sandbox) ? ddEUCJ : ddSJIS,
                          src, dst);
    }

    return detectedDecoder.decodeLoop(src, dst);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:70,代碼來源:JISAutoDetect.java

示例14: decode

import java.nio.charset.Charset; //導入方法依賴的package包/類
static char[] decode(Charset cs, byte[] ba, int off, int len) {
    // (1)We never cache the "external" cs, the only benefit of creating
    // an additional StringDe/Encoder object to wrap it is to share the
    // de/encode() method. These SD/E objects are short-lifed, the young-gen
    // gc should be able to take care of them well. But the best approash
    // is still not to generate them if not really necessary.
    // (2)The defensive copy of the input byte/char[] has a big performance
    // impact, as well as the outgoing result byte/char[]. Need to do the
    // optimization check of (sm==null && classLoader0==null) for both.
    // (3)getClass().getClassLoader0() is expensive
    // (4)There might be a timing gap in isTrusted setting. getClassLoader0()
    // is only chcked (and then isTrusted gets set) when (SM==null). It is
    // possible that the SM==null for now but then SM is NOT null later
    // when safeTrim() is invoked...the "safe" way to do is to redundant
    // check (... && (isTrusted || SM == null || getClassLoader0())) in trim
    // but it then can be argued that the SM is null when the opertaion
    // is started...
    CharsetDecoder cd = cs.newDecoder();
    int en = scale(len, cd.maxCharsPerByte());
    char[] ca = new char[en];
    if (len == 0)
        return ca;
    boolean isTrusted = false;
    if (System.getSecurityManager() != null) {
        if (!(isTrusted = (cs.getClass().getClassLoader0() == null))) {
            ba =  Arrays.copyOfRange(ba, off, off + len);
            off = 0;
        }
    }
    cd.onMalformedInput(CodingErrorAction.REPLACE)
      .onUnmappableCharacter(CodingErrorAction.REPLACE)
      .reset();
    if (cd instanceof ArrayDecoder) {
        int clen = ((ArrayDecoder)cd).decode(ba, off, len, ca);
        return safeTrim(ca, clen, cs, isTrusted);
    } else {
        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 safeTrim(ca, cb.position(), cs, isTrusted);
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:54,代碼來源:StringCoding.java

示例15: newBufferedReader

import java.nio.charset.Charset; //導入方法依賴的package包/類
/**
 * Opens the given url for reading returning a {@code BufferedReader} that may be
 * used to read text from the URL in an efficient manner. Bytes from the
 * file are decoded into characters using the specified charset.
 */
public static BufferedReader newBufferedReader(URL url, Charset cs) throws IOException {
    CharsetDecoder decoder = cs.newDecoder();
    Reader reader = new InputStreamReader(url.openStream(), decoder);
    return new BufferedReader(reader);
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:11,代碼來源:FileSystemUtils.java


注:本文中的java.nio.charset.Charset.newDecoder方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。