1 28 29 package com.caucho.vfs; 30 31 import java.io.IOException ; 32 33 37 public class StringReader extends StreamImpl { 38 private String string; 39 private int length; 40 private int index; 41 42 private StringReader(String string) 43 { 44 this.string = string; 46 this.length = string.length(); 47 this.index = 0; 48 } 49 50 57 public static ReadStream open(String string) 58 { 59 StringReader ss = new StringReader(string); 60 ReadStream rs = new ReadStream(ss); 61 try { 62 rs.setEncoding("UTF-8"); 63 } catch (Exception e) { 64 } 65 rs.setPath(new NullPath("string")); 66 return rs; 67 } 68 69 72 public boolean canRead() 73 { 74 return true; 75 } 76 77 public int read(byte []buf, int offset, int length) 78 throws IOException 79 { 80 char ch; 81 82 int i = 0; 83 for (; index < this.length && i < length; index++) { 84 ch = string.charAt(index); 85 86 if (ch < 0x80) { 87 buf[offset + i] = (byte) ch; 88 i++; 89 } 90 else if (i + 1 >= length) 91 break; 92 else if (ch < 0x800) { 93 buf[offset + i] = (byte) (0xc0 + (ch >> 6)); 94 buf[offset + i + 1] = (byte) (0x80 + (ch & 0x3f)); 95 i += 2; 96 } 97 else if (i + 2 >= length) 98 break; 99 else { 100 buf[offset + i] = (byte) (0xe0 + (ch >> 12)); 101 buf[offset + i + 1] = (byte) (0x80 + ((ch >> 6) & 0x3f)); 102 buf[offset + i + 2] = (byte) (0x80 + (ch & 0x3f)); 103 104 i += 3; 105 } 106 } 107 108 return i > 0 ? i : -1; 109 } 110 111 115 public int getAvailable() throws IOException 116 { 117 return length - index; 118 } 119 } 120 | Popular Tags |