Java NIO中Charset类源码

public abstract class Charsetimplements Comparable<Charset>
{private static volatile String bugLevel = null;static boolean atBugLevel(String bl) {              // package-privateif (bugLevel == null) {if (!sun.misc.VM.isBooted())return false;java.security.PrivilegedAction pa =new GetPropertyAction("sun.nio.cs.bugLevel");String value = (String)AccessController.doPrivileged(pa);bugLevel = (value != null) ? value : "";}return bugLevel.equals(bl);}private static void checkName(String s) {int n = s.length();if (!atBugLevel("1.4")) {if (n == 0)throw new IllegalCharsetNameException(s);}for (int i = 0; i < n; i++) {char c = s.charAt(i);if (c >= 'A' && c <= 'Z') continue;if (c >= 'a' && c <= 'z') continue;if (c >= '0' && c <= '9') continue;if (c == '-' && i != 0) continue;if (c == ':' && i != 0) continue;if (c == '_' && i != 0) continue;if (c == '.' && i != 0) continue;throw new IllegalCharsetNameException(s);}}/* The standard set of charsets */private static CharsetProvider standardProvider = new StandardCharsets();// Cache of the most-recently-returned charsets,// along with the names that were used to find them//private static volatile Object[] cache1 = null; // "Level 1" cacheprivate static volatile Object[] cache2 = null; // "Level 2" cacheprivate static void cache(String charsetName, Charset cs) {cache2 = cache1;cache1 = new Object[] { charsetName, cs };}// Creates an iterator that walks over the available providers, ignoring// those whose lookup or instantiation causes a security exception to be// thrown.  Should be invoked with full privileges.//private static Iterator providers() {return new Iterator() {Class c = java.nio.charset.spi.CharsetProvider.class;ClassLoader cl = ClassLoader.getSystemClassLoader();Iterator i = Service.providers(c, cl);Object next = null;private boolean getNext() {while (next == null) {try {if (!i.hasNext())return false;next = i.next();} catch (ServiceConfigurationError sce) {if (sce.getCause() instanceof SecurityException) {// Ignore security exceptionscontinue;}throw sce;}}return true;}public boolean hasNext() {return getNext();}public Object next() {if (!getNext())throw new NoSuchElementException();Object n = next;next = null;return n;}public void remove() {throw new UnsupportedOperationException();}};}// Thread-local gate to prevent recursive provider lookupsprivate static ThreadLocal gate = new ThreadLocal();private static Charset lookupViaProviders(final String charsetName) {// The runtime startup sequence looks up standard charsets as a// consequence of the VM's invocation of System.initializeSystemClass// in order to, e.g., set system properties and encode filenames.  At// that point the application class loader has not been initialized,// however, so we can't look for providers because doing so will cause// that loader to be prematurely initialized with incomplete// information.//if (!sun.misc.VM.isBooted())return null;if (gate.get() != null)// Avoid recursive provider lookupsreturn null;try {gate.set(gate);return (Charset)AccessController.doPrivileged(new PrivilegedAction() {public Object run() {for (Iterator i = providers(); i.hasNext();) {CharsetProvider cp = (CharsetProvider)i.next();Charset cs = cp.charsetForName(charsetName);if (cs != null)return cs;}return null;}});} finally {gate.set(null);}}/* The extended set of charsets */private static Object extendedProviderLock = new Object();private static boolean extendedProviderProbed = false;private static CharsetProvider extendedProvider = null;private static void probeExtendedProvider() {AccessController.doPrivileged(new PrivilegedAction() {public Object run() {try {Class epc= Class.forName("sun.nio.cs.ext.ExtendedCharsets");extendedProvider = (CharsetProvider)epc.newInstance();} catch (ClassNotFoundException x) {// Extended charsets not available// (charsets.jar not present)} catch (InstantiationException x) {throw new Error(x);} catch (IllegalAccessException x) {throw new Error(x);}return null;}});}private static Charset lookupExtendedCharset(String charsetName) {CharsetProvider ecp = null;synchronized (extendedProviderLock) {if (!extendedProviderProbed) {probeExtendedProvider();extendedProviderProbed = true;}ecp = extendedProvider;}return (ecp != null) ? ecp.charsetForName(charsetName) : null;}private static Charset lookup(String charsetName) {if (charsetName == null)throw new IllegalArgumentException("Null charset name");Object[] a;if ((a = cache1) != null && charsetName.equals(a[0]))return (Charset)a[1];// We expect most programs to use one Charset repeatedly.// We convey a hint to this effect to the VM by putting the// level 1 cache miss code in a separate method.return lookup2(charsetName);}private static Charset lookup2(String charsetName) {Object[] a;if ((a = cache2) != null && charsetName.equals(a[0])) {cache2 = cache1;cache1 = a;return (Charset)a[1];}Charset cs;if ((cs = standardProvider.charsetForName(charsetName)) != null ||(cs = lookupExtendedCharset(charsetName))           != null ||(cs = lookupViaProviders(charsetName))              != null){cache(charsetName, cs);return cs;}/* Only need to check the name if we didn't find a charset for it */checkName(charsetName);return null;}/*** Tells whether the named charset is supported. </p>*/public static boolean isSupported(String charsetName) {return (lookup(charsetName) != null);}/*** Returns a charset object for the named charset. </p>*/public static Charset forName(String charsetName) {Charset cs = lookup(charsetName);if (cs != null)return cs;throw new UnsupportedCharsetException(charsetName);}// Fold charsets from the given iterator into the given map, ignoring// charsets whose names already have entries in the map.//private static void put(Iterator i, Map m) {while (i.hasNext()) {Charset cs = (Charset)i.next();if (!m.containsKey(cs.name()))m.put(cs.name(), cs);}}/*** Constructs a sorted map from canonical charset names to charset objects.*/public static SortedMap<String,Charset> availableCharsets() {return (SortedMap)AccessController.doPrivileged(new PrivilegedAction() {public Object run() {TreeMap m = new TreeMap(ASCIICaseInsensitiveComparator.CASE_INSENSITIVE_ORDER);put(standardProvider.charsets(), m);for (Iterator i = providers(); i.hasNext();) {CharsetProvider cp = (CharsetProvider)i.next();put(cp.charsets(), m);}return Collections.unmodifiableSortedMap(m);}});}private static volatile Charset defaultCharset;/*** Returns the default charset of this Java virtual machine.*/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");}}return defaultCharset;}/* -- Instance fields and methods -- */private final String name;       // tickles a bug in oldjavacprivate final String[] aliases; // tickles a bug in oldjavacprivate Set aliasSet = null;/*** Initializes a new charset with the given canonical name and alias* set. </p>*/protected Charset(String canonicalName, String[] aliases) {checkName(canonicalName);String[] as = (aliases == null) ? new String[0] : aliases;for (int i = 0; i < as.length; i++)checkName(as[i]);this.name = canonicalName;this.aliases = as;}/*** Returns this charset's canonical name. </p>*/public final String name() {return name;}/*** Returns a set containing this charset's aliases. </p>*/public final Set<String> aliases() {if (aliasSet != null)return aliasSet;int n = aliases.length;HashSet hs = new HashSet(n);for (int i = 0; i < n; i++)hs.add(aliases[i]);aliasSet = Collections.unmodifiableSet(hs);return aliasSet;}/*** Returns this charset's human-readable name for the default locale.*/public String displayName() {return name;}/*** Tells whether or not this charset is registered in the <a* href="http://www.iana.org/assignments/character-sets">IANA Charset* Registry</a>.  </p>*/public final boolean isRegistered() {return !name.startsWith("X-") && !name.startsWith("x-");}/*** Returns this charset's human-readable name for the given locale.*/public String displayName(Locale locale) {return name;}/*** Tells whether or not this charset contains the given charset.*/public abstract boolean contains(Charset cs);/*** Constructs a new decoder for this charset. </p>*/public abstract CharsetDecoder newDecoder();/*** Constructs a new encoder for this charset. </p>*/public abstract CharsetEncoder newEncoder();/*** Tells whether or not this charset supports encoding.*/public boolean canEncode() {return true;}/*** Convenience method that decodes bytes in this charset into Unicode* characters.*/public final CharBuffer decode(ByteBuffer bb) {try {return ThreadLocalCoders.decoderFor(this).onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE).decode(bb);} catch (CharacterCodingException x) {throw new Error(x);        // Can't happen}}/*** Convenience method that encodes Unicode characters into bytes in this* charset.*/public final ByteBuffer encode(CharBuffer cb) {try {return ThreadLocalCoders.encoderFor(this).onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE).encode(cb);} catch (CharacterCodingException x) {throw new Error(x);     // Can't happen}}/*** Convenience method that encodes a string into bytes in this charset.*/public final ByteBuffer encode(String str) {return encode(CharBuffer.wrap(str));}/*** Compares this charset to another.*/public final int compareTo(Charset that) {return (name().compareToIgnoreCase(that.name()));}/*** Computes a hashcode for this charset. </p>*/public final int hashCode() {return name().hashCode();}/*** Tells whether or not this object is equal to another.*/public final boolean equals(Object ob) {if (!(ob instanceof Charset))return false;if (this == ob)return true;return name.equals(((Charset)ob).name());}/*** Returns a string describing this charset. </p>*/public final String toString() {return name();}}

Java NIO中Charset类源码相关推荐

  1. Java 8 中 GZIPInputStream 类源码分析

    这是<水煮 JDK 源码>系列 的第4篇文章,计划撰写100篇关于JDK源码相关的文章 GZIPInputStream 类位于 java.util.zip 包下,继承于 InflaterI ...

  2. java.lang中String类源码分析

    一.类 public final class String:final关键字说明String类不能被修改(不能被其他类继承和重写) public final class Stringimplement ...

  3. Java String类源码阅读笔记

    文章目录 一.前置 二.String类源码解析 1.String类继承关系 2.成员变量 3.构造方法 4.长度/判空 5.取字符 6.比较 7.包含 8.hashCode 9.查询索引 10.获取子 ...

  4. java的String类源码详解

    java的String类源码详解 类的定义 public final class Stringimplements java.io.Serializable, Comparable<String ...

  5. java.lang 源码剖析_java.lang.Void类源码解析

    在一次源码查看ThreadGroup的时候,看到一段代码,为以下: /* * @throws NullPointerException if the parent argument is {@code ...

  6. 【java】浅析JDK中ServiceLoader的源码

    1.概述 转载:浅析JDK中ServiceLoader的源码 上一篇文章:深入探讨 Java 类加载器 2.ServiceLoader的使用 这里先列举一个经典的例子,MySQL的Java驱动就是通过 ...

  7. java的数组与Arrays类源码详解

    java的数组与Arrays类源码详解 java.util.Arrays 类是 JDK 提供的一个工具类,用来处理数组的各种方法,而且每个方法基本上都是静态方法,能直接通过类名Arrays调用. 类的 ...

  8. java中jooq,在Spring中使用jOOQ源码案例

    Spring专题 在Spring中使用jOOQ源码案例 虽然ORM大部分性能问题是由开发者自己引起的,以只读方式使用ORM是不值得的,现在有一种其他可选方式,使用JOOQ,jOOQ从您的数据库生成Ja ...

  9. Java文件– java.nio.file.Files类

    Java Files class was introduced in Java 1.7 and is a part of java.nio.file package. Java Files类是Java ...

最新文章

  1. javascript语言学习
  2. j2ee与mysql乱码过滤_mysql 在 j2ee中配置的乱码问题处理
  3. 树莓派和windows的FileZillla文件共享,补充:树莓派图形Xrdp界面登录
  4. c 运行js脚本语言,Javascript脚本语言
  5. Adapter中notify(),notifyAll(),notifyDataSetChanged(),notifyDataSetInvalidaded()方法的区别
  6. matlab fft变换后的相位精度问题_MATLAB曲线拟合及Fourier分析
  7. Bex5常用方法总结
  8. Fibonacci Additions (区间加优化)
  9. 利用保利威视实现教育视频预览和购买
  10. Java中的十大组织
  11. pip不是内部 pycharm_解决'pip' 不是内部或外部命令,也不是可运行的程序或批处理文件的问题...
  12. 图解分布式一致性协议 Paxos 算法【BAT 面试题宝库附详尽答案解析】
  13. apple iMac一体机 装双系统 实战! (Apple +Win 7 64bit)Good
  14. 一个小时学会 MySQL 数据库
  15. SAP 在表T043G中,XXXX 的输入丢失
  16. 详解pandas中的groupy机制
  17. 请更换备份电池 pos机_UPS电池维护与保养
  18. 问题 G: 懒羊羊吃草
  19. BI软件中的管理驾驶舱是什么?有什么特点?
  20. 2020年最新 iPad Pro上的激光雷达是什么?来激光SLAM技术中找答案

热门文章

  1. 淘宝一键直达微博链接
  2. unity 程序获得焦点_Mac上的2D动画制作工具Moho Pro 12 for Mac独特的动画程序
  3. 服务器系统叹号灯,叹号故障灯是指什么意思
  4. import sympy
  5. 2013年微软Imagine Cup大赛最佳主席组织奖
  6. 数据库地区表sql语句,数据库地区表包含省市县
  7. 电脑安装了双系统(Win10+Ubuntu18.04)无法识别优盘的问题
  8. Incorrect string value XF0 X9F X98 XB3 XE3 for column 解决办法
  9. 影视后期制作技巧汇总
  10. ext中的fireEvent事件