下面列出了java.io.DataInputStream#available ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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;
}
}
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);
}
}
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;
}
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;
}
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;
}
}
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;
}
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");
}
}
public void readContent( DataInputStream in, ClassLoader loader )
throws IOException
{
while ( in.available( ) > 0 )
{
int filedId = IOUtil.readShort( in );
readField( filedId, in, loader );
}
}
protected void readGrid( DataInputStream in, GridItemDesign grid )
throws IOException
{
while ( in.available( ) > 0 )
{
short fieldType = IOUtil.readShort( in );
readGridField( in, grid, fieldType );
}
}
protected void readTableGroup( DataInputStream in,
TableGroupDesign tableGroup ) throws IOException
{
while ( in.available( ) > 0 )
{
short fieldType = IOUtil.readShort( in );
readTableGroupField( in, tableGroup, fieldType );
}
}
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;
}
/**
* 获取信息头信息,该方法会执行读取头长度
*
* @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;
}
protected void readAutoText( DataInputStream in, AutoTextItemDesign autoText )
throws IOException
{
while ( in.available( ) > 0 )
{
short fieldType = IOUtil.readShort( in );
readAutoTextField( in, autoText, fieldType );
}
}
protected void readRow( DataInputStream in, RowDesign row )
throws IOException
{
while ( in.available( ) > 0 )
{
short fieldType = IOUtil.readShort( in );
readRowField( in, row, fieldType );
}
}
/**
* @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;
}
/**
* 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;
}
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;
}
}
}
}
}
}
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);
}
}
}
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);
}
}
}