A class for turning a character stream into a byte stream. Data written to the target input stream is converted into bytes by either a default or a provided character converter. The default encoding is taken from the "file.encoding" system property. OutputStreamWriter contains a buffer of by
| 37 | * @see InputStreamReader |
| 38 | */ |
| 39 | public class OutputStreamWriter extends Writer { |
| 40 | |
| 41 | private OutputStream out; |
| 42 | |
| 43 | private CharsetEncoder encoder; |
| 44 | |
| 45 | private ByteBuffer bytes = ByteBuffer.allocate(8192); |
| 46 | |
| 47 | private boolean encoderFlush = false; |
| 48 | |
| 49 | /** |
| 50 | * Constructs a new OutputStreamWriter using {@code out} as the target |
| 51 | * stream to write converted characters to. The default character encoding |
| 52 | * is used. |
| 53 | * |
| 54 | * @param out |
| 55 | * the non-null target stream to write converted bytes to. |
| 56 | */ |
| 57 | public OutputStreamWriter(OutputStream out) { |
| 58 | super(out); |
| 59 | this.out = out; |
| 60 | // String encoding = AccessController |
| 61 | // .doPrivileged(new PriviAction<String>( |
| 62 | // "file.encoding", "ISO8859_1")); //$NON-NLS-1$ //$NON-NLS-2$ |
| 63 | String encoding = "UTF-8"; |
| 64 | encoder = Charset.forName(encoding).newEncoder(); |
| 65 | encoder.onMalformedInput(CodingErrorAction.REPLACE); |
| 66 | encoder.onUnmappableCharacter(CodingErrorAction.REPLACE); |
| 67 | } |
| 68 | |
| 69 | /** |
| 70 | * Constructs a new OutputStreamWriter using {@code out} as the target |
| 71 | * stream to write converted characters to and {@code enc} as the character |
| 72 | * encoding. If the encoding cannot be found, an |
| 73 | * UnsupportedEncodingException error is thrown. |
| 74 | * |
| 75 | * @param out |
| 76 | * the target stream to write converted bytes to. |
| 77 | * @param enc |
| 78 | * the string describing the desired character encoding. |
| 79 | * @throws NullPointerException |
| 80 | * if {@code enc} is {@code null}. |
| 81 | * @throws UnsupportedEncodingException |
| 82 | * if the encoding specified by {@code enc} cannot be found. |
| 83 | */ |
| 84 | public OutputStreamWriter(OutputStream out, final String enc) |
| 85 | throws UnsupportedEncodingException { |
| 86 | super(out); |
| 87 | if (enc == null) { |
| 88 | throw new NullPointerException(); |
| 89 | } |
| 90 | this.out = out; |
| 91 | try { |
| 92 | encoder = Charset.forName(enc).newEncoder(); |
| 93 | } catch (Exception e) { |
| 94 | throw new UnsupportedEncodingException(enc); |
| 95 | } |
| 96 | encoder.onMalformedInput(CodingErrorAction.REPLACE); |