java.io.DataInputStream#available ( )源码实例Demo

下面列出了java.io.DataInputStream#available ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: android-kernel-tweaker   文件: CMDProcessor.java
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;
}
 
源代码2 项目: nifi-minifi   文件: WholeConfigDifferentiator.java
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;
    }
}
 
源代码3 项目: jstarcraft-core   文件: CodecDefinition.java
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);
    }
}
 
源代码4 项目: CameraViewer   文件: RecorderPlayer.java
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;
}
 
源代码5 项目: translationstudio8   文件: FileUtils.java
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;
}
 
源代码6 项目: settlers-remake   文件: ImageIndexTexture.java
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;
	}
}
 
源代码7 项目: Bats   文件: FSAgent.java
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;
}
 
源代码8 项目: kudu-ts   文件: Tagsets.java
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");
  }
}
 
源代码9 项目: birt   文件: ReportContent.java
public void readContent( DataInputStream in, ClassLoader loader )
		throws IOException
{
	while ( in.available( ) > 0 )
	{
		int filedId = IOUtil.readShort( in );
		readField( filedId, in, loader );
	}
}
 
源代码10 项目: birt   文件: EngineIRReaderImpl.java
protected void readGrid( DataInputStream in, GridItemDesign grid )
		throws IOException
{
	while ( in.available( ) > 0 )
	{
		short fieldType = IOUtil.readShort( in );
		readGridField( in, grid, fieldType );
	}
}
 
源代码11 项目: birt   文件: EngineIRReaderImpl.java
protected void readTableGroup( DataInputStream in,
		TableGroupDesign tableGroup ) throws IOException
{
	while ( in.available( ) > 0 )
	{
		short fieldType = IOUtil.readShort( in );
		readTableGroupField( in, tableGroup, fieldType );
	}
}
 
源代码12 项目: bazel   文件: PersistentMap.java
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;
}
 
源代码13 项目: jstarcraft-core   文件: MessageHead.java
/**
 * 获取信息头信息,该方法会执行读取头长度
 * 
 * @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;
}
 
源代码14 项目: birt   文件: EngineIRReaderImpl.java
protected void readAutoText( DataInputStream in, AutoTextItemDesign autoText )
		throws IOException
{
	while ( in.available( ) > 0 )
	{
		short fieldType = IOUtil.readShort( in );
		readAutoTextField( in, autoText, fieldType );
	}
}
 
源代码15 项目: birt   文件: EngineIRReaderImpl.java
protected void readRow( DataInputStream in, RowDesign row )
		throws IOException
{
	while ( in.available( ) > 0 )
	{
		short fieldType = IOUtil.readShort( in );
		readRowField( in, row, fieldType );
	}
}
 
源代码16 项目: gemfirexd-oss   文件: RemoteFetchKeysMessage.java
/**
 * @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;
}
 
源代码17 项目: MeteoInfo   文件: MapDataManage.java
/**
 * 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;
}
 
源代码18 项目: consulo   文件: ValueContainerImpl.java
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;
          }
        }
      }
    }
  }
}
 
源代码19 项目: gemfirexd-oss   文件: FetchKeysMessage.java
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);
    }
  }
}
 
源代码20 项目: gemfirexd-oss   文件: FetchEntriesMessage.java
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);
    }
  }
}