Charsets.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.lang3;

  18. import java.nio.charset.Charset;
  19. import java.nio.charset.UnsupportedCharsetException;

  20. /**
  21.  * Internal use only.
  22.  * <p>
  23.  * Provides utilities for {@link Charset}.
  24.  * </p>
  25.  * <p>
  26.  * Package private since Apache Commons IO already provides a Charsets because {@link Charset} is in
  27.  * {@code java.nio.charset}.
  28.  * </p>
  29.  *
  30.  * @since 3.10
  31.  */
  32. final class Charsets {

  33.     /**
  34.      * Returns the given {@code charset} or the default Charset if {@code charset} is null.
  35.      *
  36.      * @param charset a Charset or null.
  37.      * @return the given {@code charset} or the default Charset if {@code charset} is null.
  38.      */
  39.     static Charset toCharset(final Charset charset) {
  40.         return charset == null ? Charset.defaultCharset() : charset;
  41.     }

  42.     /**
  43.      * Returns the given {@code charset} or the default Charset if {@code charset} is null.
  44.      *
  45.      * @param charsetName a Charset or null.
  46.      * @return the given {@code charset} or the default Charset if {@code charset} is null.
  47.      * @throws UnsupportedCharsetException If no support for the named charset is available in this instance of the Java
  48.      *                                     virtual machine
  49.      */
  50.     static Charset toCharset(final String charsetName) {
  51.         return charsetName == null ? Charset.defaultCharset() : Charset.forName(charsetName);
  52.     }

  53.     /**
  54.      * Returns the given {@code charset} or the default Charset if {@code charset} is null.
  55.      *
  56.      * @param charsetName a Charset or null.
  57.      * @return the given {@code charset} or the default Charset if {@code charset} is null.
  58.      */
  59.     static String toCharsetName(final String charsetName) {
  60.         return charsetName == null ? Charset.defaultCharset().name() : charsetName;
  61.     }

  62. }