1 9 package org.jrobin.core.jrrd; 10 11 import java.io.*; 12 13 24 public class RRDFile implements Constants { 25 26 boolean bigEndian; 27 int alignment; 28 RandomAccessFile ras; 29 byte[] buffer; 30 31 RRDFile(String name) throws IOException { 32 this(new File(name)); 33 } 34 35 RRDFile(File file) throws IOException { 36 37 ras = new RandomAccessFile(file, "r"); 38 buffer = new byte[128]; 39 40 initDataLayout(file); 41 } 42 43 private void initDataLayout(File file) throws IOException { 44 45 if (file.exists()) { ras.read(buffer, 0, 24); 47 48 int index; 49 50 if ((index = indexOf(FLOAT_COOKIE_BIG_ENDIAN, buffer)) != -1) { 51 bigEndian = true; 52 } else if ((index = indexOf(FLOAT_COOKIE_LITTLE_ENDIAN, buffer)) 53 != -1) { 54 bigEndian = false; 55 } else { 56 throw new IOException("Invalid RRD file"); 57 } 58 59 switch (index) { 60 61 case 12: 62 alignment = 4; 63 break; 64 65 case 16: 66 alignment = 8; 67 break; 68 69 default : 70 throw new RuntimeException ("Unsupported architecture"); 71 } 72 } else { } 74 75 ras.seek(0); } 77 78 private int indexOf(byte[] pattern, byte[] array) { 79 return (new String (array)).indexOf(new String (pattern)); 80 } 81 82 boolean isBigEndian() { 83 return bigEndian; 84 } 85 86 int getAlignment() { 87 return alignment; 88 } 89 90 double readDouble() throws IOException { 91 92 byte[] tx = new byte[8]; 94 95 ras.read(buffer, 0, 8); 96 97 if (bigEndian) { 98 tx = buffer; 99 } else { 100 for (int i = 0; i < 8; i++) { 101 tx[7 - i] = buffer[i]; 102 } 103 } 104 105 DataInputStream reverseDis = 106 new DataInputStream(new ByteArrayInputStream(tx)); 107 108 return reverseDis.readDouble(); 109 } 110 111 int readInt() throws IOException { 112 return readInt(false); 113 } 114 115 int readInt(boolean dump) throws IOException { 116 117 ras.read(buffer, 0, 4); 118 119 int value; 120 121 if (bigEndian) { 122 value = (0xFF & buffer[3]) | ((0xFF & buffer[2]) << 8) 123 | ((0xFF & buffer[1]) << 16) | ((0xFF & buffer[0]) << 24); 124 } else { 125 value = (0xFF & buffer[0]) | ((0xFF & buffer[1]) << 8) 126 | ((0xFF & buffer[2]) << 16) | ((0xFF & buffer[3]) << 24); 127 } 128 129 return value; 130 } 131 132 String readString(int maxLength) throws IOException { 133 134 ras.read(buffer, 0, maxLength); 135 136 return new String (buffer, 0, maxLength).trim(); 137 } 138 139 void skipBytes(int n) throws IOException { 140 ras.skipBytes(n); 141 } 142 143 int align(int boundary) throws IOException { 144 145 int skip = (int) (boundary - (ras.getFilePointer() % boundary)) % boundary; 146 147 if (skip != 0) { 148 ras.skipBytes(skip); 149 } 150 151 return skip; 152 } 153 154 int align() throws IOException { 155 return align(alignment); 156 } 157 158 long info() throws IOException { 159 return ras.getFilePointer(); 160 } 161 162 long getFilePointer() throws IOException { 163 return ras.getFilePointer(); 164 } 165 166 void close() throws IOException { 167 ras.close(); 168 } 169 } 170 | Popular Tags |