Java Code Examples for java.io.DataInputStream#readByte()

The following examples show how to use java.io.DataInputStream#readByte() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: INode.java    From big-c with Apache License 2.0 6 votes vote down vote up
public static INode deserialize(InputStream in) throws IOException {
  if (in == null) {
    return null;
  }
  DataInputStream dataIn = new DataInputStream(in);
  FileType fileType = INode.FILE_TYPES[dataIn.readByte()];
  switch (fileType) {
  case DIRECTORY:
    in.close();
    return INode.DIRECTORY_INODE;
  case FILE:
    int numBlocks = dataIn.readInt();
    Block[] blocks = new Block[numBlocks];
    for (int i = 0; i < numBlocks; i++) {
      long id = dataIn.readLong();
      long length = dataIn.readLong();
      blocks[i] = new Block(id, length);
    }
    in.close();
    return new INode(fileType, blocks);
  default:
    throw new IllegalArgumentException("Cannot deserialize inode.");
  }    
}
 
Example 2
Source File: LockSettingsStorage.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public static PersistentData fromBytes(byte[] frpData) {
    if (frpData == null || frpData.length == 0) {
        return NONE;
    }

    DataInputStream is = new DataInputStream(new ByteArrayInputStream(frpData));
    try {
        byte version = is.readByte();
        if (version == PersistentData.VERSION_1) {
            int type = is.readByte() & 0xFF;
            int userId = is.readInt();
            int qualityForUi = is.readInt();
            byte[] payload = new byte[frpData.length - VERSION_1_HEADER_SIZE];
            System.arraycopy(frpData, VERSION_1_HEADER_SIZE, payload, 0, payload.length);
            return new PersistentData(type, userId, qualityForUi, payload);
        } else {
            Slog.wtf(TAG, "Unknown PersistentData version code: " + version);
            return NONE;
        }
    } catch (IOException e) {
        Slog.wtf(TAG, "Could not parse PersistentData", e);
        return NONE;
    }
}
 
Example 3
Source File: FileUtils.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] readFile(String fileName) {
	try {
		DataInputStream in = new DataInputStream(new BufferedInputStream(
				new FileInputStream(fileName)));
		int n = in.available();
		byte[] t = new byte[n];
		int i = 0;
		while (in.available() != 0) {
			t[i] = in.readByte();
			i++;
		}
		in.close();
		return t;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 4
Source File: MsgConnectResp.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
 * .
 * 
 * @param data
 *            byte[]
 */
public MsgConnectResp(byte[] data) {
	if (data.length == 8 + 4 + 16 + 1) {
		ByteArrayInputStream bins = new ByteArrayInputStream(data);
		DataInputStream dins = new DataInputStream(bins);
		try {
			this.setTotalLength(data.length + 4);
			this.setCommandId(dins.readInt());
			this.setSequenceId(dins.readInt());
			this.setStatus(dins.readInt());
			byte[] aiByte = new byte[16];
			dins.read(aiByte);
			this.authenticatorISMG = aiByte;
			this.version = dins.readByte();
			dins.close();
			bins.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	} else {
		logger.info("链接至IMSP,解析数据包出错,包长度不一致。长度为:" + data.length);
	}
}
 
Example 5
Source File: LayoutOptions.java    From Carbonado with Apache License 2.0 6 votes vote down vote up
/**
 * @param source can be null if empty
 */
public synchronized void decode(byte[] source) throws IOException {
    mData.clear();

    if (source == null || source.length == 0) {
        return;
    }

    ByteArrayInputStream bin = new ByteArrayInputStream(source);
    DataInputStream din = new DataInputStream(bin);

    while (bin.available() > 0) {
        byte op = din.readByte();
        switch (op) {
        default:
            throw new IOException("Unknown extra data type: " + op);
        case COMPRESSION_TYPE:
            mData.put(COMPRESSION_TYPE, din.readUTF());
            break;
        }
    }
}
 
Example 6
Source File: ConfluentSchemaRegistryCoder.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public Schema readSchema(InputStream in) throws IOException {
	DataInputStream dataInputStream = new DataInputStream(in);

	if (dataInputStream.readByte() != 0) {
		throw new IOException("Unknown data format. Magic number does not match");
	} else {
		int schemaId = dataInputStream.readInt();

		try {
			return schemaRegistryClient.getById(schemaId);
		} catch (RestClientException e) {
			throw new IOException(format("Could not find schema with id %s in registry", schemaId), e);
		}
	}
}
 
Example 7
Source File: Nbt.java    From mapwriter with MIT License 5 votes vote down vote up
public static Nbt readNextElement(DataInputStream dis) throws IOException {
	byte tagID;
	String name = "";
	
	// fully formed tag
	tagID = (byte) dis.readByte();
	if (tagID != TAG_END) {
		// END tags do not have a name
		name = dis.readUTF();
	}
	
	return readElementData(dis, tagID, name);
}
 
Example 8
Source File: CFSA2.java    From morfologik-stemming with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Reads an automaton from a byte stream.
 */
CFSA2(InputStream stream) throws IOException {
   DataInputStream in = new DataInputStream(stream);

	// Read flags.
	short flagBits = in.readShort();
	flags = EnumSet.noneOf(FSAFlags.class);
	for (FSAFlags f : FSAFlags.values()) {
	    if (f.isSet(flagBits)) {
	        flags.add(f);
	    }
	}

	if (flagBits != FSAFlags.asShort(flags)) {
	    throw new IOException("Unrecognized flags: 0x" + Integer.toHexString(flagBits));
	}

	this.hasNumbers = flags.contains(FSAFlags.NUMBERS);

	/*
	 * Read mapping dictionary.
	 */
	int labelMappingSize = in.readByte() & 0xff;
	labelMapping = new byte[labelMappingSize];
	in.readFully(labelMapping);

	/*
	 * Read arcs' data.
	 */
	arcs = readRemaining(in);		
}
 
Example 9
Source File: AbstractBlock.java    From djl with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void loadParameters(NDManager manager, DataInputStream is)
        throws IOException, MalformedModelException {
    byte loadVersion = is.readByte();
    loadMetadata(loadVersion, is);
    for (Parameter parameter : parameters.values()) {
        parameter.load(manager, is);
    }
    for (Block child : children.values()) {
        child.loadParameters(manager, is);
    }
}
 
Example 10
Source File: Packbits.java    From icafe with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param in data input stream to read packbits data stream from
 * @param outb byte buffer to place unpacked byte data to.
 * It is assumed that unpackbits is called with outb big enough
 * for a single sequence of compressed bytes
 **/
public static void unpackbits(DataInputStream in, byte[] outb) 
	throws ArrayStoreException, ArrayIndexOutOfBoundsException,	IOException
{
	//		int i;		// input index
	int o;		// output index
	int b;		// RLE compression marker byte
	byte rep;	// byte to replicate as required
	int end;	// end of byte replication run index

	//		i = 0;
	o = 0;
	for (o = 0; o < outb.length;)	// for all input compressed data
	{
		//b = inb[i++];
		b = in.readByte();
		if (b >= 0)					// duplicate bytes
		{
			++b;	//P.rt(" copy:"+b);// convert to copy length
			//System.arraycopy(inb, i, outb, o, b);
			for (int j = 0; j < b; ++j)
				outb[o + j] = in.readByte();
			//				i += b;					// new input location
			o += b;					// new output location
		}
		else if (b != -128) 		// replicate a byte
		{
			//P.rt(" rep:"+(-b+1));	// -b + 1  is repetition count				
			//				rep = inb[i++];	//P.rt(" r:"+rep);	// repetition byte
			rep = in.readByte();
			end = o - b + 1;		// end of replication index
			for (; o < end; ++o)
				outb[o] = rep;
		}
		// if b == -128 do nothing
	}
}
 
Example 11
Source File: DnsMessage.java    From android-netdiag with MIT License 5 votes vote down vote up
private static Record readRecord(DataInputStream dis, byte[] data) throws IOException {
        readName(dis, data);
        int type = dis.readUnsignedShort();
//            class
        dis.readUnsignedShort();

        long ttl = (((long) dis.readUnsignedShort()) << 16) +
                dis.readUnsignedShort();
        int payloadLength = dis.readUnsignedShort();
        String payload = null;
        switch (type) {
            case Record.TYPE_A:
                byte[] ip = new byte[4];
                dis.readFully(ip);
                payload = InetAddress.getByAddress(ip).getHostAddress();
                break;
            case Record.TYPE_CNAME:
                payload = readName(dis, data);
                break;
            default:
                payload = null;
                for (int i = 0; i < payloadLength; i++) {
                    dis.readByte();
                }
                break;
        }
        if (payload == null) {
            throw new UnknownHostException("no record");
        }
        return new Record(payload, type, (int) ttl, System.currentTimeMillis() / 1000);
    }
 
Example 12
Source File: DataChecksum.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * This constructs a DataChecksum by reading HEADER_LEN bytes from input
 * stream <i>in</i>
 */
public static DataChecksum newDataChecksum( DataInputStream in )
                               throws IOException {
  int type = in.readByte();
  int bpc = in.readInt();
  DataChecksum summer = newDataChecksum(Type.valueOf(type), bpc );
  if ( summer == null ) {
    throw new IOException( "Could not create DataChecksum of type " +
                           type + " with bytesPerChecksum " + bpc );
  }
  return summer;
}
 
Example 13
Source File: SetMaterialPrioritiesGuiTask.java    From settlers-remake with MIT License 5 votes vote down vote up
@Override
protected void deserializeTask(DataInputStream dis) throws IOException {
	super.deserializeTask(dis);
	managerPosition = SimpleGuiTask.deserializePosition(dis);

	int length = dis.readInt();
	materialTypeForPriority = new EMaterialType[length];
	for (int i = 0; i < length; i++) {
		materialTypeForPriority[i] = EMaterialType.VALUES[dis.readByte()];
	}
}
 
Example 14
Source File: IeFixedTestBitPattern.java    From ICS-TestBed-Framework with GNU General Public License v3.0 4 votes vote down vote up
IeFixedTestBitPattern(DataInputStream is) throws IOException {
    if ((is.readByte() & 0xff) != 0x55 || (is.readByte() & 0xff) != 0xaa) {
        throw new IOException("Incorrect bit pattern in Fixed Test Bit Pattern.");
    }
}
 
Example 15
Source File: WarcRecord.java    From lucene4ir with Apache License 2.0 4 votes vote down vote up
private static byte[] readNextRecord(DataInputStream in, StringBuffer headerBuffer) throws IOException {
  if (in==null) { return null; }
  if (headerBuffer==null) { return null; }

  String line=null;
  boolean foundMark=false;    
  byte[] retContent=null;

  // cannot be using a buffered reader here!!!!
  // just read the header
  // first - find our WARC header
  while ((!foundMark) && ((line=readLineFromInputStream(in))!=null)) {
    if (line.startsWith(WARC_VERSION)) {
      WARC_VERSION_LINE = line;
      foundMark=true;
    }
  }

  // no WARC mark?
  if (!foundMark) { return null; }
  
  // LOG.info("Found WARC_VERSION");

  int contentLength = -1;
  // read until we see contentLength then an empty line
  // (to handle malformed ClueWeb09 headers that have blank lines)
  // get the content length and set our retContent
  for (line = readLineFromInputStream(in).trim(); 
      line.length() > 0 || contentLength < 0; 
      line = readLineFromInputStream(in).trim()) {
    
    if (line.length() > 0 ) {
      headerBuffer.append(line);
      headerBuffer.append(LINE_ENDING);
      
      // find the content length designated by Content-Length: <length>
      String[] parts = line.split(":", 2);
      if (parts.length == 2 && parts[0].equals("Content-Length")) {
        try {
          contentLength=Integer.parseInt(parts[1].trim());
          // LOG.info("WARC record content length: " + contentLength);
        } catch (NumberFormatException nfEx) {
          contentLength=-1;
        }
      }
    }
  }
  
  // now read the bytes of the content
  retContent=new byte[contentLength];
  int totalWant=contentLength;
  int totalRead=0;
  //
  // LOOP TO REMOVE LEADING CR * LF 
  // To prevent last few characters from being cut off of the content
  // when reading
  //
  while ((totalRead == 0) && (totalRead < contentLength)) {
    byte CR = in.readByte();
    byte LF = in.readByte();
    if ((CR != 13) && (LF != 10)) {
      retContent[0] = CR;
      retContent[1] = LF;
      totalRead = 2;
      totalWant = contentLength - totalRead;
    }
  }
  //
  //
  //
  while (totalRead < contentLength) {
     try {
      int numRead=in.read(retContent, totalRead, totalWant);
      if (numRead < 0) {
        return null;
      } else {
        totalRead += numRead;
        totalWant = contentLength-totalRead;
      } // end if (numRead < 0) / else
    } catch (EOFException eofEx) {
      // resize to what we have
      if (totalRead > 0) {
        byte[] newReturn=new byte[totalRead];
        System.arraycopy(retContent, 0, newReturn, 0, totalRead);
        return newReturn;
      } else {
        return null;
      }
     } // end try/catch (EOFException)
  } // end while (totalRead < contentLength)

  return retContent;
}
 
Example 16
Source File: EditableResources.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
void readRenderingHint(DataInputStream i) throws IOException {
    renderingHint = EditorFont.RENDERING_HINTS[i.readByte()];
}
 
Example 17
Source File: MapDataManage.java    From MeteoInfo with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Read GrADS map file
 *
 * @param aFile The file path
 * @return The layer
 * @throws java.io.FileNotFoundException
 */
public static VectorLayer readMapFile_GrADS(String aFile) throws FileNotFoundException, IOException, Exception {
    DataInputStream br = new DataInputStream(new BufferedInputStream(new FileInputStream(new File(aFile))));
    int i, lineNum;
    byte b;
    short N, lType;
    double lon, lat;
    byte[] bytes;

    PointD aPoint;
    List<PointD> pList = new ArrayList<>();

    VectorLayer aLayer = new VectorLayer(ShapeTypes.Polyline);
    String columnName = "Value";
    Field aDC = new Field(columnName, DataType.INT);
    aLayer.editAddField(aDC);

    lineNum = 0;
    do {
        b = br.readByte();    // 1-data, 2-skip
        if ("2".equals(Byte.toString(b))) {
            br.skipBytes(18);
            continue;
        }
        b = br.readByte();    // Line type: country, river ...
        lType = (short) DataConvert.byte2Int(b);
        b = br.readByte();   // Point number
        N = (short) DataConvert.byte2Int(b);
        for (i = 0; i < N; i++) {
            bytes = new byte[3];
            br.read(bytes);    //Longitude
            int val = 0;
            for (int bb = 0; bb < 3; bb++) {
                val <<= 8;
                val |= (int) bytes[bb] & 0xFF;
            }
            lon = val / 10000.0;

            bytes = new byte[3];
            br.read(bytes);    //Latitude
            val = 0;
            for (int bb = 0; bb < 3; bb++) {
                val <<= 8;
                val |= (int) bytes[bb] & 0xFF;
            }
            lat = val / 10000.0 - 90.0;

            aPoint = new PointD();
            aPoint.X = lon;
            aPoint.Y = lat;
            pList.add(aPoint);
        }
        if (pList.size() > 1) {
            PolylineShape aPolyline = new PolylineShape();
            aPolyline.setValue(lineNum);
            aPolyline.setPoints(pList);
            aPolyline.setExtent(MIMath.getPointsExtent(pList));
            aPolyline.setPartNum(1);
            aPolyline.parts = new int[1];
            aPolyline.parts[0] = 0;

            int shapeNum = aLayer.getShapeNum();
            if (aLayer.editInsertShape(aPolyline, shapeNum)) {
                aLayer.editCellValue(columnName, shapeNum, lineNum);
            }

            lineNum++;
        }
        pList = new ArrayList<>();

    } while (br.available() > 0);

    br.close();

    aLayer.setLayerName(new File(aFile).getName());
    aLayer.setFileName(aFile);
    aLayer.setLayerDrawType(LayerDrawType.Map);
    aLayer.setLegendScheme(LegendManage.createSingleSymbolLegendScheme(ShapeTypes.Polyline, Color.darkGray, 1.0F));
    aLayer.setVisible(true);

    return aLayer;
}
 
Example 18
Source File: ZoneInfoFile.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Loads the rules from a DateInputStream
 *
 * @param dis  the DateInputStream to load, not null
 * @throws Exception if an error occurs
 */
private static void load(DataInputStream dis) throws ClassNotFoundException, IOException {
    if (dis.readByte() != 1) {
        throw new StreamCorruptedException("File format not recognised");
    }
    // group
    String groupId = dis.readUTF();
    if ("TZDB".equals(groupId) == false) {
        throw new StreamCorruptedException("File format not recognised");
    }
    // versions, only keep the last one
    int versionCount = dis.readShort();
    for (int i = 0; i < versionCount; i++) {
        versionId = dis.readUTF();

    }
    // regions
    int regionCount = dis.readShort();
    String[] regionArray = new String[regionCount];
    for (int i = 0; i < regionCount; i++) {
        regionArray[i] = dis.readUTF();
    }
    // rules
    int ruleCount = dis.readShort();
    ruleArray = new byte[ruleCount][];
    for (int i = 0; i < ruleCount; i++) {
        byte[] bytes = new byte[dis.readShort()];
        dis.readFully(bytes);
        ruleArray[i] = bytes;
    }
    // link version-region-rules, only keep the last version, if more than one
    for (int i = 0; i < versionCount; i++) {
        regionCount = dis.readShort();
        regions = new String[regionCount];
        indices = new int[regionCount];
        for (int j = 0; j < regionCount; j++) {
            regions[j] = regionArray[dis.readShort()];
            indices[j] = dis.readShort();
        }
    }
    // remove the following ids from the map, they
    // are exclued from the "old" ZoneInfo
    zones.remove("ROC");
    for (int i = 0; i < versionCount; i++) {
        int aliasCount = dis.readShort();
        aliases.clear();
        for (int j = 0; j < aliasCount; j++) {
            String alias = regionArray[dis.readShort()];
            String region = regionArray[dis.readShort()];
            aliases.put(alias, region);
        }
    }
    // old us time-zone names
    addOldMapping();
}
 
Example 19
Source File: UNICAST.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
    type=in.readByte();
    seqno=in.readLong();
}
 
Example 20
Source File: LZMAInputStream.java    From LocalGSMLocationProvider with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new .lzma file format decompressor with an optional
 * memory usage limit.
 *
 * @param       in          input stream from which .lzma data is read;
 *                          it might be a good idea to wrap it in
 *                          <code>BufferedInputStream</code>, see the
 *                          note at the top of this page
 *
 * @param       memoryLimit memory usage limit in kibibytes (KiB)
 *                          or <code>-1</code> to impose no
 *                          memory usage limit
 *
 * @throws      CorruptedInputException
 *                          file is corrupt or perhaps not in
 *                          the .lzma format at all
 *
 * @throws      UnsupportedOptionsException
 *                          dictionary size or uncompressed size is too
 *                          big for this implementation
 *
 * @throws      MemoryLimitException
 *                          memory usage limit was exceeded
 *
 * @throws      EOFException
 *                          file is truncated or perhaps not in
 *                          the .lzma format at all
 *
 * @throws      IOException may be thrown by <code>in</code>
 */
public LZMAInputStream(InputStream in, int memoryLimit)
        throws IOException {
    DataInputStream inData = new DataInputStream(in);

    // Properties byte (lc, lp, and pb)
    byte propsByte = inData.readByte();

    // Dictionary size is an unsigned 32-bit little endian integer.
    int dictSize = 0;
    for (int i = 0; i < 4; ++i)
        dictSize |= inData.readUnsignedByte() << (8 * i);

    // Uncompressed size is an unsigned 64-bit little endian integer.
    // The maximum 64-bit value is a special case (becomes -1 here)
    // which indicates that the end marker is used instead of knowing
    // the uncompressed size beforehand.
    long uncompSize = 0;
    for (int i = 0; i < 8; ++i)
        uncompSize |= (long)inData.readUnsignedByte() << (8 * i);

    // Check the memory usage limit.
    int memoryNeeded = getMemoryUsage(dictSize, propsByte);
    if (memoryLimit != -1 && memoryNeeded > memoryLimit)
        throw new MemoryLimitException(memoryNeeded, memoryLimit);

    initialize(in, uncompSize, propsByte, dictSize, null);
}