InputStreamReader.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. /* InputStreamReader.java -- Reader than transforms bytes to chars
  2. Copyright (C) 1998, 1999, 2001, 2003, 2004, 2005, 2006
  3. Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.io;
  33. import gnu.classpath.SystemProperties;
  34. import gnu.java.nio.charset.EncodingHelper;
  35. import java.nio.ByteBuffer;
  36. import java.nio.CharBuffer;
  37. import java.nio.charset.Charset;
  38. import java.nio.charset.CharsetDecoder;
  39. import java.nio.charset.CoderResult;
  40. import java.nio.charset.CodingErrorAction;
  41. /**
  42. * This class reads characters from a byte input stream. The characters
  43. * read are converted from bytes in the underlying stream by a
  44. * decoding layer. The decoding layer transforms bytes to chars according
  45. * to an encoding standard. There are many available encodings to choose
  46. * from. The desired encoding can either be specified by name, or if no
  47. * encoding is selected, the system default encoding will be used. The
  48. * system default encoding name is determined from the system property
  49. * <code>file.encoding</code>. The only encodings that are guaranteed to
  50. * be availalbe are "8859_1" (the Latin-1 character set) and "UTF8".
  51. * Unforunately, Java does not provide a mechanism for listing the
  52. * ecodings that are supported in a given implementation.
  53. * <p>
  54. * Here is a list of standard encoding names that may be available:
  55. * <p>
  56. * <ul>
  57. * <li>8859_1 (ISO-8859-1/Latin-1)</li>
  58. * <li>8859_2 (ISO-8859-2/Latin-2)</li>
  59. * <li>8859_3 (ISO-8859-3/Latin-3)</li>
  60. * <li>8859_4 (ISO-8859-4/Latin-4)</li>
  61. * <li>8859_5 (ISO-8859-5/Latin-5)</li>
  62. * <li>8859_6 (ISO-8859-6/Latin-6)</li>
  63. * <li>8859_7 (ISO-8859-7/Latin-7)</li>
  64. * <li>8859_8 (ISO-8859-8/Latin-8)</li>
  65. * <li>8859_9 (ISO-8859-9/Latin-9)</li>
  66. * <li>ASCII (7-bit ASCII)</li>
  67. * <li>UTF8 (UCS Transformation Format-8)</li>
  68. * <li>More later</li>
  69. * </ul>
  70. * <p>
  71. * It is recommended that applications do not use
  72. * <code>InputStreamReader</code>'s
  73. * directly. Rather, for efficiency purposes, an object of this class
  74. * should be wrapped by a <code>BufferedReader</code>.
  75. * <p>
  76. * Due to a deficiency the Java class library design, there is no standard
  77. * way for an application to install its own byte-character encoding.
  78. *
  79. * @see BufferedReader
  80. * @see InputStream
  81. *
  82. * @author Robert Schuster
  83. * @author Aaron M. Renn (arenn@urbanophile.com)
  84. * @author Per Bothner (bothner@cygnus.com)
  85. * @date April 22, 1998.
  86. */
  87. public class InputStreamReader extends Reader
  88. {
  89. /**
  90. * The input stream.
  91. */
  92. private InputStream in;
  93. /**
  94. * The charset decoder.
  95. */
  96. private CharsetDecoder decoder;
  97. /**
  98. * End of stream reached.
  99. */
  100. private boolean isDone = false;
  101. /**
  102. * Need this.
  103. */
  104. private float maxBytesPerChar;
  105. /**
  106. * Buffer holding surplus loaded bytes (if any)
  107. */
  108. private ByteBuffer byteBuffer;
  109. /**
  110. * java.io canonical name of the encoding.
  111. */
  112. private String encoding;
  113. /**
  114. * We might decode to a 2-char UTF-16 surrogate, which won't fit in the
  115. * output buffer. In this case we need to save the surrogate char.
  116. */
  117. private char savedSurrogate;
  118. private boolean hasSavedSurrogate = false;
  119. /**
  120. * A byte array to be reused in read(byte[], int, int).
  121. */
  122. private byte[] bytesCache;
  123. /**
  124. * Locks the bytesCache above in read(byte[], int, int).
  125. */
  126. private Object cacheLock = new Object();
  127. /**
  128. * This method initializes a new instance of <code>InputStreamReader</code>
  129. * to read from the specified stream using the default encoding.
  130. *
  131. * @param in The <code>InputStream</code> to read from
  132. */
  133. public InputStreamReader(InputStream in)
  134. {
  135. if (in == null)
  136. throw new NullPointerException();
  137. this.in = in;
  138. try
  139. {
  140. encoding = SystemProperties.getProperty("file.encoding");
  141. // Don't use NIO if avoidable
  142. if(EncodingHelper.isISOLatin1(encoding))
  143. {
  144. encoding = "ISO8859_1";
  145. maxBytesPerChar = 1f;
  146. decoder = null;
  147. return;
  148. }
  149. Charset cs = EncodingHelper.getCharset(encoding);
  150. decoder = cs.newDecoder();
  151. encoding = EncodingHelper.getOldCanonical(cs.name());
  152. try {
  153. maxBytesPerChar = cs.newEncoder().maxBytesPerChar();
  154. } catch(UnsupportedOperationException _){
  155. maxBytesPerChar = 1f;
  156. }
  157. decoder.onMalformedInput(CodingErrorAction.REPLACE);
  158. decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
  159. decoder.reset();
  160. } catch(RuntimeException e) {
  161. encoding = "ISO8859_1";
  162. maxBytesPerChar = 1f;
  163. decoder = null;
  164. } catch(UnsupportedEncodingException e) {
  165. encoding = "ISO8859_1";
  166. maxBytesPerChar = 1f;
  167. decoder = null;
  168. }
  169. }
  170. /**
  171. * This method initializes a new instance of <code>InputStreamReader</code>
  172. * to read from the specified stream using a caller supplied character
  173. * encoding scheme. Note that due to a deficiency in the Java language
  174. * design, there is no way to determine which encodings are supported.
  175. *
  176. * @param in The <code>InputStream</code> to read from
  177. * @param encoding_name The name of the encoding scheme to use
  178. *
  179. * @exception UnsupportedEncodingException If the encoding scheme
  180. * requested is not available.
  181. */
  182. public InputStreamReader(InputStream in, String encoding_name)
  183. throws UnsupportedEncodingException
  184. {
  185. if (in == null
  186. || encoding_name == null)
  187. throw new NullPointerException();
  188. this.in = in;
  189. // Don't use NIO if avoidable
  190. if(EncodingHelper.isISOLatin1(encoding_name))
  191. {
  192. encoding = "ISO8859_1";
  193. maxBytesPerChar = 1f;
  194. decoder = null;
  195. return;
  196. }
  197. try {
  198. Charset cs = EncodingHelper.getCharset(encoding_name);
  199. try {
  200. maxBytesPerChar = cs.newEncoder().maxBytesPerChar();
  201. } catch(UnsupportedOperationException _){
  202. maxBytesPerChar = 1f;
  203. }
  204. decoder = cs.newDecoder();
  205. decoder.onMalformedInput(CodingErrorAction.REPLACE);
  206. decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
  207. decoder.reset();
  208. // The encoding should be the old name, if such exists.
  209. encoding = EncodingHelper.getOldCanonical(cs.name());
  210. } catch(RuntimeException e) {
  211. encoding = "ISO8859_1";
  212. maxBytesPerChar = 1f;
  213. decoder = null;
  214. }
  215. }
  216. /**
  217. * Creates an InputStreamReader that uses a decoder of the given
  218. * charset to decode the bytes in the InputStream into
  219. * characters.
  220. *
  221. * @since 1.4
  222. */
  223. public InputStreamReader(InputStream in, Charset charset) {
  224. if (in == null)
  225. throw new NullPointerException();
  226. this.in = in;
  227. decoder = charset.newDecoder();
  228. try {
  229. maxBytesPerChar = charset.newEncoder().maxBytesPerChar();
  230. } catch(UnsupportedOperationException _){
  231. maxBytesPerChar = 1f;
  232. }
  233. decoder.onMalformedInput(CodingErrorAction.REPLACE);
  234. decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
  235. decoder.reset();
  236. encoding = EncodingHelper.getOldCanonical(charset.name());
  237. }
  238. /**
  239. * Creates an InputStreamReader that uses the given charset decoder
  240. * to decode the bytes in the InputStream into characters.
  241. *
  242. * @since 1.4
  243. */
  244. public InputStreamReader(InputStream in, CharsetDecoder decoder) {
  245. if (in == null)
  246. throw new NullPointerException();
  247. this.in = in;
  248. this.decoder = decoder;
  249. Charset charset = decoder.charset();
  250. try {
  251. if (charset == null)
  252. maxBytesPerChar = 1f;
  253. else
  254. maxBytesPerChar = charset.newEncoder().maxBytesPerChar();
  255. } catch(UnsupportedOperationException _){
  256. maxBytesPerChar = 1f;
  257. }
  258. decoder.onMalformedInput(CodingErrorAction.REPLACE);
  259. decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
  260. decoder.reset();
  261. if (charset == null)
  262. encoding = "US-ASCII";
  263. else
  264. encoding = EncodingHelper.getOldCanonical(decoder.charset().name());
  265. }
  266. /**
  267. * This method closes this stream, as well as the underlying
  268. * <code>InputStream</code>.
  269. *
  270. * @exception IOException If an error occurs
  271. */
  272. public void close() throws IOException
  273. {
  274. synchronized (lock)
  275. {
  276. // Makes sure all intermediate data is released by the decoder.
  277. if (decoder != null)
  278. decoder.reset();
  279. if (in != null)
  280. in.close();
  281. in = null;
  282. isDone = true;
  283. decoder = null;
  284. }
  285. }
  286. /**
  287. * This method returns the name of the encoding that is currently in use
  288. * by this object. If the stream has been closed, this method is allowed
  289. * to return <code>null</code>.
  290. *
  291. * @return The current encoding name
  292. */
  293. public String getEncoding()
  294. {
  295. return in != null ? encoding : null;
  296. }
  297. /**
  298. * This method checks to see if the stream is ready to be read. It
  299. * will return <code>true</code> if is, or <code>false</code> if it is not.
  300. * If the stream is not ready to be read, it could (although is not required
  301. * to) block on the next read attempt.
  302. *
  303. * @return <code>true</code> if the stream is ready to be read,
  304. * <code>false</code> otherwise
  305. *
  306. * @exception IOException If an error occurs
  307. */
  308. public boolean ready() throws IOException
  309. {
  310. if (in == null)
  311. throw new IOException("Reader has been closed");
  312. return in.available() != 0;
  313. }
  314. /**
  315. * This method reads up to <code>length</code> characters from the stream into
  316. * the specified array starting at index <code>offset</code> into the
  317. * array.
  318. *
  319. * @param buf The character array to recieve the data read
  320. * @param offset The offset into the array to start storing characters
  321. * @param length The requested number of characters to read.
  322. *
  323. * @return The actual number of characters read, or -1 if end of stream.
  324. *
  325. * @exception IOException If an error occurs
  326. */
  327. public int read(char[] buf, int offset, int length) throws IOException
  328. {
  329. if (in == null)
  330. throw new IOException("Reader has been closed");
  331. if (isDone)
  332. return -1;
  333. if(decoder != null)
  334. {
  335. int totalBytes = (int)((double) length * maxBytesPerChar);
  336. if (byteBuffer != null)
  337. totalBytes = Math.max(totalBytes, byteBuffer.remaining());
  338. byte[] bytes;
  339. // Fetch cached bytes array if available and big enough.
  340. synchronized(cacheLock)
  341. {
  342. bytes = bytesCache;
  343. if (bytes == null || bytes.length < totalBytes)
  344. bytes = new byte[totalBytes];
  345. else
  346. bytesCache = null;
  347. }
  348. int remaining = 0;
  349. if(byteBuffer != null)
  350. {
  351. remaining = byteBuffer.remaining();
  352. byteBuffer.get(bytes, 0, remaining);
  353. }
  354. int read;
  355. if(totalBytes - remaining > 0)
  356. {
  357. read = in.read(bytes, remaining, totalBytes - remaining);
  358. if(read == -1){
  359. read = remaining;
  360. isDone = true;
  361. } else
  362. read += remaining;
  363. } else
  364. read = remaining;
  365. byteBuffer = ByteBuffer.wrap(bytes, 0, read);
  366. CharBuffer cb = CharBuffer.wrap(buf, offset, length);
  367. int startPos = cb.position();
  368. if(hasSavedSurrogate){
  369. hasSavedSurrogate = false;
  370. cb.put(savedSurrogate);
  371. read++;
  372. }
  373. CoderResult cr = decoder.decode(byteBuffer, cb, isDone);
  374. decoder.reset();
  375. // 1 char remains which is the first half of a surrogate pair.
  376. if(cr.isOverflow() && cb.hasRemaining()){
  377. CharBuffer overflowbuf = CharBuffer.allocate(2);
  378. cr = decoder.decode(byteBuffer, overflowbuf, isDone);
  379. overflowbuf.flip();
  380. if(overflowbuf.hasRemaining())
  381. {
  382. cb.put(overflowbuf.get());
  383. savedSurrogate = overflowbuf.get();
  384. hasSavedSurrogate = true;
  385. isDone = false;
  386. }
  387. }
  388. if(byteBuffer.hasRemaining()) {
  389. byteBuffer.compact();
  390. byteBuffer.flip();
  391. isDone = false;
  392. } else
  393. byteBuffer = null;
  394. read = cb.position() - startPos;
  395. // Put cached bytes array back if we are finished and the cache
  396. // is null or smaller than the used bytes array.
  397. synchronized (cacheLock)
  398. {
  399. if (byteBuffer == null
  400. && (bytesCache == null || bytesCache.length < bytes.length))
  401. bytesCache = bytes;
  402. }
  403. return (read <= 0) ? -1 : read;
  404. }
  405. else
  406. {
  407. byte[] bytes;
  408. // Fetch cached bytes array if available and big enough.
  409. synchronized (cacheLock)
  410. {
  411. bytes = bytesCache;
  412. if (bytes == null || length < bytes.length)
  413. bytes = new byte[length];
  414. else
  415. bytesCache = null;
  416. }
  417. int read = in.read(bytes);
  418. for(int i=0;i<read;i++)
  419. buf[offset+i] = (char)(bytes[i]&0xFF);
  420. // Put back byte array into cache if appropriate.
  421. synchronized (cacheLock)
  422. {
  423. if (bytesCache == null || bytesCache.length < bytes.length)
  424. bytesCache = bytes;
  425. }
  426. return read;
  427. }
  428. }
  429. /**
  430. * Reads an char from the input stream and returns it
  431. * as an int in the range of 0-65535. This method also will return -1 if
  432. * the end of the stream has been reached.
  433. * <p>
  434. * This method will block until the char can be read.
  435. *
  436. * @return The char read or -1 if end of stream
  437. *
  438. * @exception IOException If an error occurs
  439. */
  440. public int read() throws IOException
  441. {
  442. char[] buf = new char[1];
  443. int count = read(buf, 0, 1);
  444. return count > 0 ? buf[0] : -1;
  445. }
  446. /**
  447. * Skips the specified number of chars in the stream. It
  448. * returns the actual number of chars skipped, which may be less than the
  449. * requested amount.
  450. *
  451. * @param count The requested number of chars to skip
  452. *
  453. * @return The actual number of chars skipped.
  454. *
  455. * @exception IOException If an error occurs
  456. */
  457. public long skip(long count) throws IOException
  458. {
  459. if (in == null)
  460. throw new IOException("Reader has been closed");
  461. return super.skip(count);
  462. }
  463. }