1 /*======================================================================*
2 * Copyright (c) 2008, Yahoo! Inc. All rights reserved. *
4 * Licensed under the New BSD License (the "License"); you may not use *
5 * this file except in compliance with the License. Unless required *
6 * by applicable law or agreed to in writing, software distributed *
7 * under the License is distributed on an "AS IS" BASIS, WITHOUT *
8 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
9 * See the License for the specific language governing permissions and *
10 * limitations under the License. See accompanying LICENSE file. *
11 *======================================================================*/
13 package org
.lwes
.util
;
15 import java
.io
.UnsupportedEncodingException
;
18 * EncodedString is a wrapper class which wraps a String, but replaces all
19 * methods using a string representation of a character encoding with
20 * ones using the CharacterEncoding class, thereby guaranteeing
21 * validity and eliminating the need to throw any exceptions.
23 * @author Kevin Scaldeferri
27 public class EncodedString
{
28 private String myString
;
29 private CharacterEncoding myEncoding
;
31 public static String
bytesToString(byte[] bytes
, CharacterEncoding enc
) {
37 return new String(bytes
, enc
.getEncodingString());
38 } catch (UnsupportedEncodingException e
) {
39 throw new IllegalArgumentException("Unknown Encoding");
43 public static String
bytesToString(byte[] bytes
, int offset
, int length
, CharacterEncoding enc
) {
49 return new String(bytes
, offset
, length
, enc
.getEncodingString());
50 } catch (UnsupportedEncodingException e
) {
51 throw new IllegalArgumentException("Unknown Encoding");
55 public static byte[] getBytes(String string
, CharacterEncoding enc
) {
61 return string
.getBytes(enc
.getEncodingString());
62 } catch (UnsupportedEncodingException e
) {
63 throw new IllegalArgumentException("Unknown Encoding");
67 public EncodedString(String string
, CharacterEncoding enc
) {
72 public EncodedString(byte[] bytes
, CharacterEncoding enc
) {
73 myString
= bytesToString(bytes
, enc
);
77 public EncodedString(byte[] bytes
, int offset
,
78 int length
, CharacterEncoding enc
)
80 myString
= bytesToString(bytes
, offset
, length
, enc
);
84 public byte[] getBytes() { return getBytes(myString
, myEncoding
); }
85 public String
toString() { return myString
; }