Throw a RuntimeExcecption instead of calling System.exit in one of the constructors...
[lwes-java.git] / src / org / lwes / util / EncodedString.java
blobc6bf99d9190b7c685108679a5192bd6238e61ca2
1 package org.lwes.util;
3 import java.io.UnsupportedEncodingException;
5 /**
6 * EncodedString is a wrapper class which wraps a String, but replaces all
7 * methods using a string representation of a character encoding with
8 * ones using the CharacterEncoding class, thereby guaranteeing
9 * validity and eliminating the need to throw any exceptions.
11 * @author Kevin Scaldeferri
12 * @version %I%, %G%
13 * @since 0.0.1
15 public class EncodedString {
16 private String myString;
17 private CharacterEncoding myEncoding;
19 public static String bytesToString(byte[] bytes, CharacterEncoding enc) {
20 String ret = null;
21 try {
22 ret = new String(bytes, enc.getEncodingString());
23 } catch (UnsupportedEncodingException e) {
24 throw new IllegalArgumentException("Unknown Encoding");
25 } catch (NullPointerException e) {
26 return null;
28 return ret;
31 public static String bytesToString(byte[] bytes, int offset,
32 int length, CharacterEncoding enc) {
33 String ret = null;
34 try {
35 ret = new String(bytes, offset, length, enc.getEncodingString());
36 } catch (UnsupportedEncodingException e) {
37 throw new IllegalArgumentException("Unknown Encoding");
38 } catch (NullPointerException e) {
39 return null;
41 return ret;
44 public static byte[] getBytes(String string, CharacterEncoding enc) {
45 byte[] ret = null;
46 try {
47 ret = string.getBytes(enc.getEncodingString());
48 } catch (UnsupportedEncodingException e) {
49 throw new IllegalArgumentException("Unknown Encoding");
50 } catch (NullPointerException e) {
51 return null;
53 return ret;
56 public EncodedString(String string, CharacterEncoding enc) {
57 myString = string;
58 myEncoding = enc;
61 public EncodedString(byte[] bytes, CharacterEncoding enc) {
62 myString = bytesToString(bytes, enc);
63 myEncoding = enc;
66 public EncodedString(byte[] bytes, int offset,
67 int length, CharacterEncoding enc)
69 myString = bytesToString(bytes, offset, length, enc);
70 myEncoding = enc;
73 public byte[] getBytes() { return getBytes(myString, myEncoding); }
74 public String toString() { return myString; }