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

The following examples show how to use java.io.DataInputStream#available() . 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: CMDProcessor.java    From android-kernel-tweaker with GNU General Public License v3.0 7 votes vote down vote up
private String getStreamLines(final InputStream is) {
    String out = null;
    StringBuffer buffer = null;
    final DataInputStream dis = new DataInputStream(is);

    try {
        if (dis.available() > 0) {
            buffer = new StringBuffer(dis.readLine());
            while (dis.available() > 0) {
                buffer.append("\n").append(dis.readLine());
            }
        }
        dis.close();
    } catch (final Exception ex) {
        Log.e(TAG, ex.getMessage());
    }
    if (buffer != null) {
        out = buffer.toString();
    }
    return out;
}
 
Example 2
Source File: CodecDefinition.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
public static CodecDefinition fromBytes(byte[] bytes) {
    try {
        CodecDefinition definition = new CodecDefinition();
        // 解压解密
        byte[] unzip = PressUtility.unzip(bytes, 30, TimeUnit.SECONDS);

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(unzip);
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
        int size = dataInputStream.readInt();
        definition.code2Definitions = new ArrayList<>(size);
        while (dataInputStream.available() > 0) {
            ClassDefinition classDefinition = ClassDefinition.readFrom(dataInputStream);
            Type clazz = classDefinition.getType();
            definition.code2Definitions.add(classDefinition);
            definition.type2Definitions.put(clazz, classDefinition);
        }
        return definition;
    } catch (Exception exception) {
        throw new CodecDefinitionException(exception);
    }
}
 
Example 3
Source File: ImageIndexTexture.java    From settlers-remake with MIT License 6 votes vote down vote up
private void loadTexture(GLDrawContext gl) {
	try {
		final DataInputStream in = new DataInputStream(new BufferedInputStream(file));
		int i = in.available() / 2;
		final int height = nextLowerPOT(Math.sqrt(i));
		final int width = nextLowerPOT(i / height);

		// TODO: Use better buffering.
		final ShortBuffer data = ByteBuffer.allocateDirect(width * height * 2).order(ByteOrder.nativeOrder()).asShortBuffer();
		while (data.hasRemaining()) {
			data.put(in.readShort());
		}
		data.rewind();
		textureIndex = gl.generateTexture(width, height, data, name);
	} catch (final IOException e) {
		e.printStackTrace();
		textureIndex = null;
	}
}
 
Example 4
Source File: FileUtils.java    From translationstudio8 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 5
Source File: RecorderPlayer.java    From CameraViewer with Apache License 2.0 6 votes vote down vote up
public int getVideoLength() throws IOException {
    int index = 0;
    mDataInputStream = new DataInputStream(new FileInputStream(mFile));
    mFrameLength = new int[1000];
    while (mDataInputStream.available() > 0) {
        int size = mDataInputStream.readInt();//帧长度
        mFrameLength[index++] = mDataInputStream.readInt();//图像停留时间
        mDataInputStream.skipBytes(size);//跳过图像数据
        //空间不够,要扩充
        if (index == mFrameLength.length) {
            int[] tmp = new int[mFrameLength.length + 1000];
            for (int j = 0; j < index; j++) {
                tmp[j] = mFrameLength[j];
            }
            mFrameLength = tmp;
        }
    }
    mDataInputStream.close();
    return index;
}
 
Example 6
Source File: WholeConfigDifferentiator.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
boolean compareInputStreamToConfigFile(InputStream inputStream) throws IOException {
    logger.debug("Checking if change is different");
    AtomicReference<ByteBuffer> currentConfigFileReference = configurationFileHolder.getConfigFileReference();
    ByteBuffer currentConfigFile = currentConfigFileReference.get();
    ByteBuffer byteBuffer = ByteBuffer.allocate(currentConfigFile.limit());
    DataInputStream dataInputStream = new DataInputStream(inputStream);
    try {
        dataInputStream.readFully(byteBuffer.array());
    } catch (EOFException e) {
        logger.debug("New config is shorter than the current. Must be different.");
        return true;
    }
    logger.debug("Read the input");

    if (dataInputStream.available() != 0) {
        return true;
    } else {
        return byteBuffer.compareTo(currentConfigFile) != 0;
    }
}
 
Example 7
Source File: ReportContent.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public void readContent( DataInputStream in, ClassLoader loader )
		throws IOException
{
	while ( in.available( ) > 0 )
	{
		int filedId = IOUtil.readShort( in );
		readField( filedId, in, loader );
	}
}
 
Example 8
Source File: EngineIRReaderImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
protected void readGrid( DataInputStream in, GridItemDesign grid )
		throws IOException
{
	while ( in.available( ) > 0 )
	{
		short fieldType = IOUtil.readShort( in );
		readGridField( in, grid, fieldType );
	}
}
 
Example 9
Source File: FSAgent.java    From Bats with Apache License 2.0 5 votes vote down vote up
public byte[] readFullFileContent(Path path) throws IOException
{
  DataInputStream is = new DataInputStream(fileSystem.open(path));
  byte[] bytes = new byte[is.available()];
  try {
    is.readFully(bytes);
  } finally {
    is.close();
  }
  return bytes;
}
 
Example 10
Source File: EngineIRReaderImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
protected void readTableGroup( DataInputStream in,
		TableGroupDesign tableGroup ) throws IOException
{
	while ( in.available( ) > 0 )
	{
		short fieldType = IOUtil.readShort( in );
		readTableGroupField( in, tableGroup, fieldType );
	}
}
 
Example 11
Source File: PersistentMap.java    From bazel with Apache License 2.0 5 votes vote down vote up
private boolean hasEntries(DataInputStream in, boolean failFast) throws IOException {
  if (in.available() <= 0) {
    return false;
  } else if (in.readUnsignedByte() != ENTRY_MAGIC) {
    if (failFast) {
      throw new IOException("Corrupted entry separator");
    } else {
      return false;
    }
  }
  return true;
}
 
Example 12
Source File: MessageHead.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * 获取信息头信息,该方法会执行读取头长度
 * 
 * @param data 信息数据
 * @return
 * @throws IOException
 */
static MessageHead fromBytes(byte[] data) throws IOException {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
    DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
    MessageHead value = new MessageHead();
    value.sequence = dataInputStream.readInt();
    value.instant = Instant.ofEpochMilli(dataInputStream.readLong());
    value.command = dataInputStream.readByte();
    value.module = new byte[dataInputStream.available()];
    dataInputStream.read(value.module);
    return value;
}
 
Example 13
Source File: EngineIRReaderImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
protected void readAutoText( DataInputStream in, AutoTextItemDesign autoText )
		throws IOException
{
	while ( in.available( ) > 0 )
	{
		short fieldType = IOUtil.readShort( in );
		readAutoTextField( in, autoText, fieldType );
	}
}
 
Example 14
Source File: EngineIRReaderImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
protected void readRow( DataInputStream in, RowDesign row )
		throws IOException
{
	while ( in.available( ) > 0 )
	{
		short fieldType = IOUtil.readShort( in );
		readRowField( in, row, fieldType );
	}
}
 
Example 15
Source File: Tagsets.java    From kudu-ts with Apache License 2.0 5 votes vote down vote up
public SortedMap<String, String> deserialize() {
  try {
    SortedMap<String, String> tags = new TreeMap<>();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
    while (dis.available() > 0) {
      tags.put(dis.readUTF(), dis.readUTF());
    }
    return tags;
  } catch (IOException e) {
    throw new RuntimeException("unreachable");
  }
}
 
Example 16
Source File: ValueContainerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void readFrom(@Nonnull DataInputStream stream, @Nonnull DataExternalizer<? extends Value> externalizer, @Nonnull IntIntFunction inputRemapping) throws IOException {
  FileId2ValueMapping<Value> mapping = null;

  while (stream.available() > 0) {
    final int valueCount = DataInputOutputUtil.readINT(stream);
    if (valueCount < 0) {
      // ChangeTrackingValueContainer marked inputId as invalidated, see ChangeTrackingValueContainer.saveTo
      final int inputId = inputRemapping.fun(-valueCount);

      if (mapping == null && size() > NUMBER_OF_VALUES_THRESHOLD) { // avoid O(NumberOfValues)
        mapping = new FileId2ValueMapping<>(this);
      }

      boolean doCompact;
      if (mapping != null) {
        doCompact = mapping.removeFileId(inputId);
      }
      else {
        removeAssociatedValue(inputId);
        doCompact = true;
      }

      if (doCompact) setNeedsCompacting(true);
    }
    else {
      for (int valueIdx = 0; valueIdx < valueCount; valueIdx++) {
        final Value value = externalizer.read(stream);
        int idCountOrSingleValue = DataInputOutputUtil.readINT(stream);

        if (idCountOrSingleValue > 0) {
          addValue(idCountOrSingleValue, value);
          if (mapping != null) mapping.associateFileIdToValue(inputRemapping.fun(idCountOrSingleValue), value);
        }
        else {
          idCountOrSingleValue = -idCountOrSingleValue;
          ChangeBufferingList changeBufferingList = ensureFileSetCapacityForValue(value, idCountOrSingleValue);
          int prev = 0;

          for (int i = 0; i < idCountOrSingleValue; i++) {
            final int id = DataInputOutputUtil.readINT(stream);
            int remappedInputId = inputRemapping.fun(prev + id);
            if (changeBufferingList != null) changeBufferingList.add(remappedInputId);
            else addValue(remappedInputId, value);
            if (mapping != null) mapping.associateFileIdToValue(remappedInputId, value);
            prev += id;
          }
        }
      }
    }
  }
}
 
Example 17
Source File: FetchKeysMessage.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
void processChunk(FetchKeysReplyMessage msg) {
  // this processing algorighm won't work well if there are multiple recipients.  currently the
  // retry logic for failed recipients is in PartitionedRegion.  If we parallelize the sending
  // of this message, we'll need to handle failover in this processor class and track results
  // differently.

  boolean doneProcessing = false;

  if (msg.getException() != null) {
    process(msg);
  }
  else {
    try {
      ByteArrayInputStream byteStream = new ByteArrayInputStream(msg.chunk);
      DataInputStream in = new DataInputStream(byteStream);
      final boolean requiresRegionContext = this.pr
          .keyRequiresRegionContext();
      while (in.available() > 0) {
        Object key = DataSerializer.readObject(in);
        if (key != null) {
          if (requiresRegionContext) {
            ((KeyWithRegionContext)key).setRegionContext(this.pr);
          }
          synchronized(returnValue) {
            returnValue.add(key);
          }
        }
        else {
          // null should signal the end of the set of keys
          Assert.assertTrue(in.available() == 0);
        }
      }
  
      synchronized(this.endLock) {
        chunksProcessed = chunksProcessed + 1;
  
        if (((msg.seriesNum+1) == msg.numSeries)  &&  msg.lastInSeries) {
          lastChunkReceived = true;
          chunksExpected = msg.msgNum + 1;
        }
  
        if (lastChunkReceived  &&  (chunksExpected == chunksProcessed)) {
          doneProcessing = true;
        }
        if (DistributionManager.VERBOSE) {
          getDistributionManager().getLoggerI18n().fine(String.valueOf(this) + " chunksProcessed="+chunksProcessed
            +",lastChunkReceived="+lastChunkReceived + ",chunksExpected="+chunksExpected
            +",done="+doneProcessing);
        }
      }
    }
    catch (Exception e) {
      processException(new ReplyException(LocalizedStrings.FetchKeysMessage_ERROR_DESERIALIZING_KEYS.toLocalizedString(), e));
      checkIfDone(); // fix for hang in 41202
    }
  
    // if all chunks have been received, wake up the waiting thread
    if (doneProcessing) {
      process(msg);
    }
  }
}
 
Example 18
Source File: FetchEntriesMessage.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
void processChunk(FetchEntriesReplyMessage msg) {
  // this processing algorighm won't work well if there are multiple recipients.  currently the
  // retry logic for failed recipients is in PartitionedRegion.  If we parallelize the sending
  // of this message, we'll need to handle failover in this processor class and track results
  // differently.

  boolean doneProcessing = false;
  
  if (msg.getException() != null) {
    process(msg);
  }
  else {
    boolean deserializingKey = true;
    try {
      ByteArrayInputStream byteStream = new ByteArrayInputStream(msg.chunk);
      DataInputStream in = new DataInputStream(byteStream);
      final boolean requiresRegionContext = this.pr
          .keyRequiresRegionContext();
      Object key;
      
      while (in.available() > 0) {
        deserializingKey = true;
        key = DataSerializer.readObject(in);
        if (key != null) {
          if (requiresRegionContext) {
            ((KeyWithRegionContext)key).setRegionContext(this.pr);
          }
          deserializingKey = false;
          Object value = DataSerializer.readObject(in);
          VersionTag versionTag = DataSerializer.readObject(in);
          if (versionTag != null) {
            //Fix for 47260 - canonicalize the mebmer ids to avoid an OOME
            if(canonicalMembers.containsKey(versionTag.getMemberID())) {
              versionTag.setMemberID(canonicalMembers.get(versionTag.getMemberID()));
            } else {
              canonicalMembers.put(versionTag.getMemberID(), versionTag.getMemberID());
            }
          } else { // is this block even needed?
            if (!canonicalMembers.containsKey(msg.getSender())) {
              canonicalMembers.put(msg.getSender(), msg.getSender());
            }
          }
          
          synchronized(returnValue) {
            returnValue.put(key, value);
            returnVersions.put(key, versionTag);
          }
        }
        else {
          // null should signal the end of the set of keys
          Assert.assertTrue(in.available() == 0);
        }
      }
  
      synchronized(this.endLock) {
        chunksProcessed = chunksProcessed + 1;
  
        if (((msg.seriesNum+1) == msg.numSeries)  &&  msg.lastInSeries) {
          chunksExpected = msg.msgNum + 1;
          lastChunkReceived = true;
        }
  
        if (allMessagesReceived(msg.hasRVV)) {
          doneProcessing = true;
        }
        if (DistributionManager.VERBOSE) {
          getDistributionManager().getLoggerI18n().fine(String.valueOf(this) + " chunksProcessed="+chunksProcessed
            +",lastChunkReceived="+lastChunkReceived + ",chunksExpected="+chunksExpected
            +",done="+doneProcessing);
        }
      }
    }
    catch (Exception e) {
      if (deserializingKey) {
        processException(new ReplyException(LocalizedStrings.FetchEntriesMessage_ERROR_DESERIALIZING_KEYS.toLocalizedString(), e));
      } else {
        processException(new ReplyException(LocalizedStrings.FetchEntriesMessage_ERROR_DESERIALIZING_VALUES.toLocalizedString(), e)); // for bug 41202
      }
      checkIfDone(); // fix for hang in 41202
    }
  
    // if all chunks have been received, wake up the waiting thread
    if (doneProcessing) {
      process(msg);
    }
  }
}
 
Example 19
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 20
Source File: RemoteFetchKeysMessage.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * @param msg
 * @return true if done processing
 */
boolean processChunk(RemoteFetchKeysReplyMessage msg) {
  // this processing algorighm won't work well if there are multiple recipients.  currently the
  // retry logic for failed recipients is in PartitionedRegion.  If we parallelize the sending
  // of this message, we'll need to handle failover in this processor class and track results
  // differently.

  boolean doneProcessing = false;
  try {
    
    ByteArrayInputStream byteStream = new ByteArrayInputStream(msg.chunk);
    DataInputStream in = new DataInputStream(byteStream);
    final boolean requiresRegionContext = this.region
        .keyRequiresRegionContext();
    while (in.available() > 0) {
      Object key = DataSerializer.readObject(in);
      if (key != null) {
        if (requiresRegionContext) {
          ((KeyWithRegionContext)key).setRegionContext(this.region);
        }
        synchronized(returnValue) {
          returnValue.add(key);
        }
      }
      else {
        // null should signal the end of the set of keys
        Assert.assertTrue(in.available() == 0);
      }
    }

    synchronized(this.endLock) {
      chunksProcessed = chunksProcessed + 1;

      if (((msg.seriesNum+1) == msg.numSeries)  &&  msg.lastInSeries) {
        lastChunkReceived = true;
        chunksExpected = msg.msgNum + 1;
      }

      if (lastChunkReceived  &&  (chunksExpected == chunksProcessed)) {
        doneProcessing = true;
      }
      if (DistributionManager.VERBOSE) {
        getDistributionManager().getLoggerI18n().fine(String.valueOf(this) + " chunksProcessed="+chunksProcessed
          +",lastChunkReceived="+lastChunkReceived + ",chunksExpected="+chunksExpected
          +",done="+doneProcessing);
      }
    }
  }
  catch (Exception e) {
    processException(new ReplyException(LocalizedStrings.FetchKeysMessage_ERROR_DESERIALIZING_KEYS.toLocalizedString(), e));
  }
  return doneProcessing;
}