KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > vfs > StringStream


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  * Free SoftwareFoundation, Inc.
23  * 59 Temple Place, Suite 330
24  * Boston, MA 02111-1307 USA
25  *
26  * @author Scott Ferguson
27  */

28
29 package com.caucho.vfs;
30
31 import java.io.IOException JavaDoc;
32
33 public class StringStream extends StreamImpl {
34   private String JavaDoc _string;
35   private int _length;
36   private int _index;
37
38   StringStream(String JavaDoc string)
39   {
40     // this.path = new NullPath("string");
41
_string = string;
42     _length = string.length();
43     _index = 0;
44   }
45
46   public static ReadStream open(String JavaDoc string)
47   {
48     StringStream ss = new StringStream(string);
49     return new ReadStream(ss);
50   }
51
52   public Path getPath() { return new StringPath(_string); }
53
54   public boolean canRead() { return true; }
55
56   // XXX: encoding issues
57
public int read(byte []buf, int offset, int length) throws IOException JavaDoc
58   {
59     if (_length - _index < length)
60       length = _length - _index;
61
62     for (int i = 0; i < length; i++) {
63       int ch = _string.charAt(_index + i);
64
65       if (ch < 0x80)
66     buf[offset++] = (byte) ch;
67       else if (ch < 0x800) {
68     buf[offset++] = (byte) (0xc0 | (ch >> 6));
69     buf[offset++] = (byte) (0x80 | (ch & 0x3f));
70       }
71       else if (ch < 0x8000) {
72     buf[offset++] = (byte) (0xe0 | (ch >> 12));
73     buf[offset++] = (byte) (0x80 | ((ch >> 6) & 0x3f));
74     buf[offset++] = (byte) (0x80 | ((ch >> 6) & 0x3f));
75       }
76     }
77
78     _index += length;
79
80     return length > 0 ? length : -1;
81   }
82
83   public int getAvailable() throws IOException JavaDoc
84   {
85     return _length - _index;
86   }
87 }
88
Popular Tags