File tree Expand file tree Collapse file tree
main/java/org/apache/commons/codec
test/java/org/apache/commons/codec Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1717package org .apache .commons .codec ;
1818
1919import java .nio .charset .Charset ;
20+ import java .nio .charset .UnsupportedCharsetException ;
2021
2122/**
2223 * Charsets required of every implementation of the Java platform.
5455 * @version $Id: CharEncoding.java 1173287 2011-09-20 18:16:19Z ggregory $
5556 */
5657public class Charsets {
58+
5759 //
5860 // This class should only contain Charset instances for required encodings. This guarantees that it will load correctly and
5961 // without delay on all Java platforms.
6062 //
63+
64+ /**
65+ * Returns the given Charset or the default Charset if the given Charset is null.
66+ *
67+ * @param charset
68+ * A charset or null.
69+ * @return the given Charset or the default Charset if the given Charset is null
70+ */
71+ public static Charset toCharset (Charset charset ) {
72+ return charset == null ? Charset .defaultCharset () : charset ;
73+ }
74+
75+ /**
76+ * Returns a Charset for the named charset. If the name is null, return the default Charset.
77+ *
78+ * @param charset
79+ * The name of the requested charset, may be null.
80+ * @return a Charset for the named charset
81+ * @throws UnsupportedCharsetException
82+ * If the named charset is unavailable
83+ */
84+ public static Charset toCharset (String charset ) {
85+ return charset == null ? Charset .defaultCharset () : Charset .forName (charset );
86+ }
87+
6188 /**
6289 * CharEncodingISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1. </p>
6390 * <p>
Original file line number Diff line number Diff line change 1717
1818package org .apache .commons .codec ;
1919
20+ import java .nio .charset .Charset ;
21+
2022import junit .framework .Assert ;
2123
2224import org .junit .Test ;
2830 */
2931public class CharsetsTest {
3032
33+ @ Test
34+ public void testToCharset () {
35+ Assert .assertEquals (Charset .defaultCharset (), Charsets .toCharset ((String ) null ));
36+ Assert .assertEquals (Charset .defaultCharset (), Charsets .toCharset ((Charset ) null ));
37+ Assert .assertEquals (Charset .defaultCharset (), Charsets .toCharset (Charset .defaultCharset ()));
38+ Assert .assertEquals (Charset .forName ("UTF-8" ), Charsets .toCharset (Charset .forName ("UTF-8" )));
39+ }
40+
3141 @ Test
3242 public void testIso8859_1 () {
3343 Assert .assertEquals ("ISO-8859-1" , Charsets .ISO_8859_1 .name ());
You can’t perform that action at this time.
0 commit comments