01: /*
02: * @(#)CharacterEncoding.java 1.2 04/12/06
03: *
04: * Copyright (c) 2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package pnuts.io;
10:
11: import pnuts.lang.Context;
12: import pnuts.lang.PnutsException;
13: import java.io.*;
14:
15: public class CharacterEncoding {
16: private final static String INPUT_CHARACTER_ENCODING = "pnuts$io$characterEncoding$in"
17: .intern();
18: private final static String OUTPUT_CHARACTER_ENCODING = "pnuts$io$characterEncoding$out"
19: .intern();
20:
21: public static Reader getReader(InputStream in, Context context) {
22: return getReader(in, null, context);
23: }
24:
25: public static Reader getReader(InputStream in, String enc,
26: Context context) {
27: if (enc == null) {
28: enc = (String) context.get(INPUT_CHARACTER_ENCODING);
29: }
30: if (enc != null) {
31: try {
32: return new InputStreamReader(in, enc);
33: } catch (UnsupportedEncodingException e) {
34: throw new PnutsException(e, context);
35: }
36: } else {
37: return new InputStreamReader(in);
38: }
39: }
40:
41: public static Writer getWriter(OutputStream out, Context context) {
42: return getWriter(out, null, context);
43: }
44:
45: public static Writer getWriter(OutputStream out, String enc,
46: Context context) {
47: if (enc == null) {
48: enc = (String) context.get(OUTPUT_CHARACTER_ENCODING);
49: }
50: if (enc != null) {
51: try {
52: return new OutputStreamWriter(out, enc);
53: } catch (UnsupportedEncodingException e) {
54: throw new PnutsException(e, context);
55: }
56: } else {
57: return new OutputStreamWriter(out);
58: }
59: }
60:
61: public static void setCharacterEncoding(String in, String out,
62: Context context) {
63: context.set(INPUT_CHARACTER_ENCODING, in);
64: context.set(OUTPUT_CHARACTER_ENCODING, out);
65: }
66:
67: public static String[] getCharacterEncoding(Context context) {
68: return new String[] {
69: (String) context.get(INPUT_CHARACTER_ENCODING),
70: (String) context.get(OUTPUT_CHARACTER_ENCODING) };
71: }
72: }
|