KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > h2 > util > ExactUTF8InputStreamReader


1 /*
2  * Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
3  * Initial Developer: H2 Group
4  */

5 package org.h2.util;
6
7 import java.io.IOException JavaDoc;
8 import java.io.InputStream JavaDoc;
9 import java.io.Reader JavaDoc;
10
11 /**
12  * The regular InputStreamReader may read some more bytes than required.
13  * If this is a problem, use this class.
14  */

15 public class ExactUTF8InputStreamReader extends Reader JavaDoc {
16     
17     private InputStream JavaDoc in;
18     
19     public ExactUTF8InputStreamReader(InputStream JavaDoc in) {
20         this.in = in;
21     }
22
23     public void close() throws IOException JavaDoc {
24     }
25
26     public int read(char[] cbuf, int off, int len) throws IOException JavaDoc {
27         for(int i=0; i<len; i++, off++) {
28             int x = in.read();
29             if(x < 0) {
30                 return i == 0 ? -1 : i;
31             }
32             x = x & 0xff;
33             if(x < 0x80) {
34                 cbuf[off] = (char)x;
35             } else if(x >= 0xe0) {
36                 cbuf[off] = (char)(((x & 0xf) << 12) + ((in.read() & 0x3f) << 6) + (in.read() & 0x3f));
37             } else {
38                 cbuf[off] = (char)(((x & 0x1f) << 6) + (in.read() & 0x3f));
39             }
40         }
41         return len;
42     }
43
44 }
45
Popular Tags