Code example for BufferedInputStream

Methods: mark, read, skip

0
		private final int offsetOriginalStrings;
		private final int offsetTranslatedStrings;
 
		public BinaryMoFileParser(InputStream is) throws IOException {
			this.is = is;
			this.reader = new BufferedInputStream(is, is.available());
			this.reader.mark(9999999);
			int magic = readIntLE();
			if (magic != 0x950412de) throw new IOException("Invalid magic in MO file");
			this.reader.skip(4);
			numStrings = readIntLE();
			offsetOriginalStrings = readIntLE();
			offsetTranslatedStrings = readIntLE();
		} 
 
		public void close() throws IOException { 
			reader.close();
			is.close();
		} 
 
		private static final String charset = "utf-8";
 
		public String translate(String s) throws IOException {
			if (numStrings <= 0) return s;
 
			byte[] bytes = s.getBytes(charset);
			byte[] translation = find(bytes);
			if (translation == null || translation.length <= 0) return s;
			return new String(translation, charset);
		} 
 
		private byte[] find(byte[] bytes) throws IOException {
			return find(bytes, 0, numStrings);
		} 
 
		private byte[] find(byte[] bytes, int minIndex, int maxIndex) throws IOException {
			int middleIndex;
			while(minIndex != maxIndex) {
				if (minIndex+1 == maxIndex) middleIndex = minIndex;
				else if (minIndex+2 == maxIndex) middleIndex = minIndex;
				else middleIndex = (minIndex + maxIndex) / 2;
 
				int c = compare(bytes, middleIndex);
				if (c == 0) return getTranslatedStringAt(middleIndex);
 
				if (minIndex+1 == maxIndex) {
					return null; 
				} else if (c > 0) {
					maxIndex = middleIndex;
				} else { 
					minIndex = middleIndex+1;
				} 
			} 
			return null; 
		} 
 
		private final byte[] buf = new byte[8];
		public final int readIntLE() throws IOException 
		{ 
			reader.read(buf, 0, 4);
			return 
					(buf[3]&0xff) << 24 |
					(buf[2]&0xff) << 16 |
					(buf[1]&0xff) <<  8 |
					(buf[0]&0xff);