1 24 25 package com.mckoi.database.global; 26 27 import java.io.IOException ; 28 import java.io.InputStream ; 29 30 36 37 public class ByteLongObject implements java.io.Serializable , BlobAccessor { 38 39 static final long serialVersionUID = -6843780673892019530L; 40 41 44 private byte[] data; 45 46 49 public ByteLongObject(byte[] from, int offset, int length) { 50 data = new byte[(int) length]; 51 System.arraycopy(from, (int) offset, data, 0, (int) length); 52 } 53 54 public ByteLongObject(byte[] from) { 55 this(from, 0, from.length); 56 } 57 58 public ByteLongObject(InputStream in, int length) throws IOException { 59 data = new byte[length]; 60 int i = 0; 61 while (i < length) { 62 int read = in.read(data, i, length - i); 63 if (read == -1) { 64 throw new IOException ("Premature end of stream."); 65 } 66 i += read; 67 } 68 } 69 70 73 public int length() { 74 return data.length; 75 } 76 77 80 public byte getByte(int n) { 81 return data[n]; 82 } 83 84 89 public byte[] getByteArray() { 90 return data; 91 } 92 93 96 public InputStream getInputStream() { 97 return new BLOBInputStream(); 98 } 99 100 public String toString() { 101 StringBuffer buf = new StringBuffer (); 102 if (data == null) { 103 buf.append("[ BLOB (NULL) ]"); 104 } 105 else { 106 buf.append("[ BLOB size="); 107 buf.append(data.length); 108 buf.append(" ]"); 109 } 110 return new String (buf); 111 } 112 113 116 private class BLOBInputStream extends InputStream { 117 118 private int index; 119 120 public BLOBInputStream() { 121 index = 0; 122 } 123 124 public int read() throws IOException { 125 if (index >= length()) { 126 return -1; 127 } 128 int b = ((int) getByte(index)) & 0x0FF; 129 ++index; 130 return b; 131 } 132 133 public int read(byte[] buf, int off, int len) throws IOException { 134 if (len == 0) { 136 return 0; 137 } 138 139 int size = length(); 140 int to_read = Math.min(len, size - index); 141 142 if (to_read <= 0) { 143 return -1; 145 } 146 147 System.arraycopy(data, index, buf, off, to_read); 148 index += to_read; 149 150 return to_read; 151 } 152 153 } 154 155 } 156 | Popular Tags |