Skip to content

Commit 778eb54

Browse files
committed
Add methods from IO.
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/codec/trunk@1307569 13f79535-47bb-0310-9956-ffa450edef68
1 parent 5819f2d commit 778eb54

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

src/main/java/org/apache/commons/codec/Charsets.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.apache.commons.codec;
1818

1919
import java.nio.charset.Charset;
20+
import java.nio.charset.UnsupportedCharsetException;
2021

2122
/**
2223
* Charsets required of every implementation of the Java platform.
@@ -54,10 +55,36 @@
5455
* @version $Id: CharEncoding.java 1173287 2011-09-20 18:16:19Z ggregory $
5556
*/
5657
public 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>

src/test/java/org/apache/commons/codec/CharsetsTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717

1818
package org.apache.commons.codec;
1919

20+
import java.nio.charset.Charset;
21+
2022
import junit.framework.Assert;
2123

2224
import org.junit.Test;
@@ -28,6 +30,14 @@
2830
*/
2931
public 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());

0 commit comments

Comments
 (0)