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

The following examples show how to use java.io.DataInputStream#readDouble() . 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: ShapeFileManage.java    From MeteoInfo with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void readHeader(DataInputStream br) throws IOException {
    int i;

    int FileCode = swapByteOrder(br.readInt());
    for (i = 0; i < 5; i++) {
        br.readInt();
    }
    int FileLength = swapByteOrder(br.readInt());
    int Version = br.readInt();
    int aShapeType = br.readInt();
    Extent aExtent = new Extent();
    aExtent.minX = br.readDouble();
    aExtent.minY = br.readDouble();
    aExtent.maxX = br.readDouble();
    aExtent.maxY = br.readDouble();
    for (i = 0; i < 4; i++) {
        br.readDouble();
    }
}
 
Example 2
Source File: FeatureIO.java    From multimedia-indexing with Apache License 2.0 6 votes vote down vote up
/**
 * Reads features from a binary file and returns them in an ArrayList<double[]>.
 * 
 * @param featuresFileName
 *            The binary file containing the features.
 * @param featureLength
 *            The length of each feature.
 * @return
 * @throws Exception
 */
public static ArrayList<double[]> readBinary(String featuresFileName, int featureLength) throws Exception {
	ArrayList<double[]> features = new ArrayList<double[]>();
	DataInputStream in = new DataInputStream(new BufferedInputStream(
			new FileInputStream(featuresFileName)));

	int counter = 0;
	double[] desc = new double[featureLength];
	while (true) {
		try {
			desc[counter] = in.readDouble();
		} catch (EOFException e) {
			break;
		}
		counter++;
		if (counter == featureLength) {
			features.add(desc);
			counter = 0;
			desc = new double[featureLength];
		}
	}
	in.close();
	return features;
}
 
Example 3
Source File: StatsUtils.java    From egads with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Decodes byte array to a double value.
 */
public static double bytesToDouble(byte [] b) {
    if (b == null) {
        return Double.NaN;
    }
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(b));
    try {
        if (b.length == 4) {
            return dis.readFloat();
        } else {
            return dis.readDouble();
        }
    } catch (IOException bad) {
        return Double.NaN;
    }
}
 
Example 4
Source File: GeometryRTree.java    From android_maplib with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void read(DataInputStream stream) throws IOException {
    mLeaf = stream.readBoolean();
    double minX = stream.readDouble();
    double minY = stream.readDouble();
    double maxX = stream.readDouble();
    double maxY = stream.readDouble();
    mCoords.setMin(minX, minY);
    mCoords.setMax(maxX, maxY);
    int size = stream.readInt();
    for(int i = 0; i < size; i++){
        if(stream.readBoolean()){
            Node childNode = new Node();
            childNode.read(stream);
            add(childNode);
        }
        else {
            Entry childEntry = new Entry();
            childEntry.read(stream);
            add(childEntry);
        }
    }
}
 
Example 5
Source File: ScanUtils.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
public static DataPoint[] decodeDataPointsFromBytes(byte bytes[]) {
  // each double is 8 bytes and we need one for m/z and one for intensity
  int dpCount = bytes.length / 2 / 8;

  // make a data input stream
  ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
  DataInputStream peakStream = new DataInputStream(byteStream);

  DataPoint dataPoints[] = new DataPoint[dpCount];

  for (int i = 0; i < dataPoints.length; i++) {
    try {
      double mz = peakStream.readDouble();
      double intensity = peakStream.readDouble();
      dataPoints[i] = new SimpleDataPoint(mz, intensity);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  return dataPoints;
}
 
Example 6
Source File: AbstractBackedByteData.java    From cfr with MIT License 5 votes vote down vote up
@Override
public double getDoubleAt(long o) throws ConfusedCFRException {
    DataInputStream dis = rawDataAsStream((int) o, 8);
    try {
        return dis.readDouble();
    } catch (Exception e) {
        throw new ConfusedCFRException(e);
    }
}
 
Example 7
Source File: CCQuantifierDataManager.java    From jatecs with GNU General Public License v3.0 5 votes vote down vote up
public IQuantifier read(IStorageManager storageManager, String modelName) {
    IClassifier classifier = classifierDataManager.read(storageManager,
            modelName + classifierSuffix);
    IClassifierRuntimeCustomizer customizer = classifierDataManager
            .readClassifierRuntimeConfiguration(storageManager, modelName
                    + classifierSuffix);
    DataInputStream reader = new DataInputStream(
            storageManager.getInputStreamForResource(modelName
                    + thresholdSuffix));
    try {
        boolean perDocument = reader.readBoolean();
        ClassificationMode classificationMode = ClassificationMode.PER_DOCUMENT;
        if (perDocument) {
            classificationMode = ClassificationMode.PER_DOCUMENT;
        } else {
            classificationMode = ClassificationMode.PER_DOCUMENT;
        }
        boolean hasThresholds = reader.readBoolean();
        if (hasThresholds) {
            TShortDoubleHashMap thresholds = new TShortDoubleHashMap();
            int count = reader.readInt();
            for (int i = 0; i < count; ++i) {
                short cat = reader.readShort();
                double value = reader.readDouble();
                thresholds.put(cat, value);
            }
            reader.close();
            return new CCQuantifier(classifier, customizer,
                    classificationMode, thresholds);
        } else {
            reader.close();
            return new CCQuantifier(classifier, customizer,
                    classificationMode);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: PacketWrapper.java    From HexxitGear with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private static Object readObjectFromStream(DataInputStream data, Class curClass) throws IOException
{
    if (curClass.equals(Boolean.class))
    {
        return data.readBoolean();
    }
    else if (curClass.equals(Byte.class))
    {
        return data.readByte();
    }
    else if (curClass.equals(Integer.class))
    {
        return data.readInt();
    }
    else if (curClass.equals(String.class))
    {
        return data.readUTF();
    }
    else if (curClass.equals(Double.class))
    {
        return data.readDouble();
    }
    else if (curClass.equals(Float.class))
    {
        return data.readFloat();
    }
    else if (curClass.equals(Long.class))
    {
        return data.readLong();
    }
    else if (curClass.equals(Short.class))
    {
        return data.readShort();
    }

    return null;
}
 
Example 9
Source File: TechList.java    From Open-Realms-of-Stars with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read TechList from DataInputStream
 * @param dis DataInputStream
 * @throws IOException if there is any problem with DataInputStream
 */
public TechList(final DataInputStream dis) throws IOException {
  techList = new TechListForLevel[TechType.values().length][MAX_TECH_LEVEL];
  for (int i = 0; i < MAX_TECH_TYPES; i++) {
    for (int j = 0; j < MAX_TECH_LEVEL; j++) {
      techList[i][j] = new TechListForLevel(j + 1, TechType.values()[i], dis);
    }
  }
  for (int i = 0; i < MAX_TECH_TYPES; i++) {
    techLevels[i] = dis.readInt();
    techFocus[i] = dis.readInt();
    techResearchPoint[i] = dis.readDouble();
  }

}
 
Example 10
Source File: MersenneTwister.java    From mars-sim with GNU General Public License v3.0 5 votes vote down vote up
/** Reads the entire state of the MersenneTwister RNG from the stream */
public synchronized void readState(DataInputStream stream) throws IOException
    {
    int len = mt.length;
    for(int x=0;x<len;x++) mt[x] = stream.readInt();
    
    len = mag01.length;
    for(int x=0;x<len;x++) mag01[x] = stream.readInt();
    
    mti = stream.readInt();
    __nextNextGaussian = stream.readDouble();
    __haveNextNextGaussian = stream.readBoolean();
    }
 
Example 11
Source File: RealFunctionValidation.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public static SummaryStatistics assessAccuracy(final Method method,
                                               final DataInputStream in,
                                               final DataOutputStream out)
    throws IOException, IllegalAccessException, IllegalArgumentException,
    InvocationTargetException {

    if (method.getReturnType() != Double.TYPE) {
        throw new IllegalArgumentException("method must return a double");
    }

    final Class<?>[] types = method.getParameterTypes();
    for (int i = 0; i < types.length; i++) {
        if (!types[i].isPrimitive()) {
            final StringBuilder builder = new StringBuilder();
            builder.append("argument #").append(i + 1)
                .append(" of method ").append(method.getName())
                .append("must be of primitive of type");
            throw new IllegalArgumentException(builder.toString());
        }
    }

    final SummaryStatistics stat = new SummaryStatistics();
    final Object[] parameters = new Object[types.length];
    while (true) {
        try {
            for (int i = 0; i < parameters.length; i++) {
                parameters[i] = readAndWritePrimitiveValue(in, out,
                                                           types[i]);
            }
            final double expected = in.readDouble();
            if (FastMath.abs(expected) > 1E-16) {
                final Object value = method.invoke(null, parameters);
                final double actual = ((Double) value).doubleValue();
                final double err = FastMath.abs(actual - expected);
                final double ulps = err / FastMath.ulp(expected);
                out.writeDouble(expected);
                out.writeDouble(actual);
                out.writeDouble(ulps);
                stat.addValue(ulps);
            }
        } catch (EOFException e) {
            break;
        }
    }
    return stat;
}
 
Example 12
Source File: BinaryConstantPool.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Constructor
 */
BinaryConstantPool(DataInputStream in) throws IOException {
    // JVM 4.1 ClassFile.constant_pool_count
    types = new byte[in.readUnsignedShort()];
    cpool = new Object[types.length];
    for (int i = 1 ; i < cpool.length ; i++) {
        int j = i;
        // JVM 4.4 cp_info.tag
        switch(types[i] = in.readByte()) {
          case CONSTANT_UTF8:
            cpool[i] = in.readUTF();
            break;

          case CONSTANT_INTEGER:
            cpool[i] = new Integer(in.readInt());
            break;
          case CONSTANT_FLOAT:
            cpool[i] = new Float(in.readFloat());
            break;
          case CONSTANT_LONG:
            cpool[i++] = new Long(in.readLong());
            break;
          case CONSTANT_DOUBLE:
            cpool[i++] = new Double(in.readDouble());
            break;

          case CONSTANT_CLASS:
          case CONSTANT_STRING:
            // JVM 4.4.3 CONSTANT_String_info.string_index
            // or JVM 4.4.1 CONSTANT_Class_info.name_index
            cpool[i] = new Integer(in.readUnsignedShort());
            break;

          case CONSTANT_FIELD:
          case CONSTANT_METHOD:
          case CONSTANT_INTERFACEMETHOD:
          case CONSTANT_NAMEANDTYPE:
            // JVM 4.4.2 CONSTANT_*ref_info.class_index & name_and_type_index
            cpool[i] = new Integer((in.readUnsignedShort() << 16) | in.readUnsignedShort());
            break;

          case CONSTANT_METHODHANDLE:
            cpool[i] = readBytes(in, 3);
            break;
          case CONSTANT_METHODTYPE:
            cpool[i] = readBytes(in, 2);
            break;
          case CONSTANT_INVOKEDYNAMIC:
            cpool[i] = readBytes(in, 4);
            break;

          case 0:
          default:
            throw new ClassFormatError("invalid constant type: " + (int)types[i]);
        }
    }
}
 
Example 13
Source File: IndexFile.java    From rtg-tools with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void loadVersion4Fields(DataInputStream indexStream, PrereadHashFunction headerHash, File dir) throws IOException {
  if (mVersion >= N_HISTOGRAM_AND_SDF_TYPE_VERSION) {
    mNBlocksCount = indexStream.readLong();
    headerHash.irvineHash(mNBlocksCount);
    mLongestNBlock = indexStream.readLong();
    headerHash.irvineHash(mLongestNBlock);
    //read N histogram
    mNHistogram = new long[SdfWriter.MAX_HISTOGRAM];
    for (int i = 0; i < mNHistogram.length; ++i) {
      mNHistogram[i] = indexStream.readLong();
      headerHash.irvineHash(mNHistogram[i]);
    }
    //read Pos histogram
    mPosHistogram = new long[SdfWriter.MAX_HISTOGRAM];
    for (int i = 0; i < mPosHistogram.length; ++i) {
      mPosHistogram[i] = indexStream.readLong();
      headerHash.irvineHash(mPosHistogram[i]);
    }
    //read QS average histogram
    mGlobalQSAverage = indexStream.readDouble();
    compatDoubleHash(headerHash, mVersion, mGlobalQSAverage);
    //headerHash.irvineHash(String.valueOf(mGlobalQSAverage));

    mPositionAverageHistogram = new double[SdfWriter.MAX_HISTOGRAM];
    for (int i = 0; i < mPositionAverageHistogram.length; ++i) {
      mPositionAverageHistogram[i] = indexStream.readDouble();
      compatDoubleHash(headerHash, mVersion, mPositionAverageHistogram[i]);
      //headerHash.irvineHash(String.valueOf(mPositionAverageHistogram[i]));
    }

    //read sdf type
    final int prereadArm = indexStream.readInt();
    if (prereadArm > PrereadArm.values().length || prereadArm < 0) {
      throw new CorruptSdfException(dir);
    }
    mPrereadArm = PrereadArm.values()[prereadArm];
    headerHash.irvineHash((long) mPrereadArm.ordinal());
    final int prereadType = indexStream.readInt();
    if (prereadType > PrereadType.values().length || prereadType < 0) {
      throw new CorruptSdfException(dir);
    }
    mPrereadType = PrereadType.values()[prereadType];
    headerHash.irvineHash((long) mPrereadType.ordinal());

    mSdfIdLowBits = indexStream.readLong();
    headerHash.irvineHash(mSdfIdLowBits);
  }
}
 
Example 14
Source File: DbImport.java    From sensorhub with Mozilla Public License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception
{
    if (args.length < 2)
    {
        System.out.println("Usage: DbImport export_file storage_path");
        System.exit(1);
    }
    
    // open storage
    String dbPath = args[1];
    BasicStorageConfig dbConf = new BasicStorageConfig();
    dbConf.enabled = true;
    dbConf.memoryCacheSize = 1024;
    dbConf.storagePath = dbPath;
    BasicStorageImpl db = new BasicStorageImpl();
    db.init(dbConf);
    db.start();
    db.setAutoCommit(false);
    
    // read XML metadata file
    File metadataFile = new File(args[0]);
    DOMHelper dom = new DOMHelper("file://" + metadataFile.getAbsolutePath(), false);
    SMLUtils smlUtils = new SMLUtils(SMLUtils.V2_0);
    SWEUtils sweUtils = new SWEUtils(SWEUtils.V2_0);
    
    // import each sensorML description
    NodeList smlElts = dom.getElements(DbConstants.SECTION_SENSORML);
    for (int i = 0; i < smlElts.getLength(); i++)
    {
        Element processElt = dom.getFirstChildElement((Element)smlElts.item(i));
        AbstractProcess process = smlUtils.readProcess(dom, processElt);
        db.storeDataSourceDescription(process);
        db.commit();
        System.out.println("Imported SensorML description " + process.getId());
    }
    
    // import data stores
    NodeList dataStoreElts = dom.getElements(DbConstants.SECTION_DATASTORE);
    for (int i = 0; i < dataStoreElts.getLength(); i++)
    {
        Element dataStoreElt = (Element)dataStoreElts.item(i);
        String recordType = dom.getAttributeValue(dataStoreElt, "name");
        Element resultStructElt = dom.getElement(dataStoreElt, "elementType/*");
        DataComponent recordStruct = sweUtils.readComponent(dom, resultStructElt);
        Element resultEncodingElt = dom.getElement(dataStoreElt, "encoding/*");
        DataEncoding recordEncoding = sweUtils.readEncoding(dom, resultEncodingElt);
        db.addRecordStore(recordType, recordStruct, recordEncoding);
        db.commit();
        System.out.println("Imported metadata for data store " + recordType);
        System.out.println("Importing records...");
        
        // read records data            
        DataStreamParser recordParser = null;
        try
        {
            File dataFile = new File(metadataFile.getParent(), recordType + ".export.data");
            InputStream recordInput = new BufferedInputStream(new FileInputStream(dataFile));
            DataInputStream dis = new DataInputStream(recordInput);
            
            // prepare record writer
            recordParser = SWEHelper.createDataParser(recordEncoding);
            recordParser.setDataComponents(recordStruct);
            recordParser.setInput(recordInput);
            
            // write all records
            int recordCount = 0;
            while (true)
            {
                try
                {
                    double timeStamp = dis.readDouble();
                    String producerID = dis.readUTF();
                    if (producerID.equals(DbConstants.KEY_NULL_PRODUCER))
                        producerID = null;
                        
                    DataKey key = new DataKey(recordType, timeStamp);
                    key.producerID = producerID;
                    DataBlock dataBlk = recordParser.parseNextBlock();
                    db.storeRecord(key, dataBlk);
                    recordCount++;
                    
                    if (recordCount % 100 == 0)
                        System.out.print(recordCount + "\r");
                }
                catch (EOFException e)
                {
                    break;
                }
            }
            
            System.out.println("Imported " + recordCount + " records");
        }
        finally
        {
            if (recordParser != null)
                recordParser.close();
            
            db.commit();
        }
    }
}
 
Example 15
Source File: RealFunctionValidation.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public static SummaryStatistics assessAccuracy(final Method method,
                                               final DataInputStream in,
                                               final DataOutputStream out)
    throws IOException, IllegalAccessException, IllegalArgumentException,
    InvocationTargetException {

    if (method.getReturnType() != Double.TYPE) {
        throw new IllegalArgumentException("method must return a double");
    }

    final Class<?>[] types = method.getParameterTypes();
    for (int i = 0; i < types.length; i++) {
        if (!types[i].isPrimitive()) {
            final StringBuilder builder = new StringBuilder();
            builder.append("argument #").append(i + 1)
                .append(" of method ").append(method.getName())
                .append("must be of primitive of type");
            throw new IllegalArgumentException(builder.toString());
        }
    }

    final SummaryStatistics stat = new SummaryStatistics();
    final Object[] parameters = new Object[types.length];
    while (true) {
        try {
            for (int i = 0; i < parameters.length; i++) {
                parameters[i] = readAndWritePrimitiveValue(in, out,
                                                           types[i]);
            }
            final double expected = in.readDouble();
            if (FastMath.abs(expected) > 1E-16) {
                final Object value = method.invoke(null, parameters);
                final double actual = ((Double) value).doubleValue();
                final double err = FastMath.abs(actual - expected);
                final double ulps = err / FastMath.ulp(expected);
                out.writeDouble(expected);
                out.writeDouble(actual);
                out.writeDouble(ulps);
                stat.addValue(ulps);
            }
        } catch (EOFException e) {
            break;
        }
    }
    return stat;
}
 
Example 16
Source File: CuckooFilter.java    From guava-probably with Apache License 2.0 4 votes vote down vote up
/**
 * Reads a byte stream, which was written by {@link #writeTo(OutputStream)}, into a {@link
 * CuckooFilter}. <p/> The {@code Funnel} to be used is not encoded in the stream, so it must be
 * provided here. <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one
 * used to populate the original Cuckoo filter!
 *
 * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not
 *                     appear to be a CuckooFilter serialized using the {@link
 *                     #writeTo(OutputStream)} method.
 */
@CheckReturnValue
public static <T> CuckooFilter<T> readFrom(InputStream in, Funnel<T> funnel) throws IOException {
  checkNotNull(in, "InputStream");
  checkNotNull(funnel, "Funnel");
  int strategyOrdinal = -1;
  double fpp = -1.0D;
  long size = -1L;
  long checksum = -1L;
  long numBuckets = -1L;
  int numEntriesPerBucket = -1;
  int numBitsPerEntry = -1;
  int dataLength = -1;
  try {
    DataInputStream din = new DataInputStream(in);
    // currently this assumes there is no negative ordinal; will have to be updated if we
    // add non-stateless strategies (for which we've reserved negative ordinals; see
    // Strategy.ordinal()).
    strategyOrdinal = din.readByte();
    fpp = din.readDouble();
    size = din.readLong();
    checksum = din.readLong();
    numBuckets = din.readLong();
    numEntriesPerBucket = din.readInt();
    numBitsPerEntry = din.readInt();
    dataLength = din.readInt();

    CuckooStrategy cuckooStrategy = CuckooStrategies.values()[strategyOrdinal].strategy();
    long[] data = new long[dataLength];
    for (int i = 0; i < data.length; i++) {
      data[i] = din.readLong();
    }
    return new CuckooFilter<T>(
        new CuckooTable(data, size, checksum, numBuckets, numEntriesPerBucket, numBitsPerEntry),
        funnel, cuckooStrategy, fpp);
  } catch (RuntimeException e) {
    IOException ioException = new IOException(
        "Unable to deserialize CuckooFilter from InputStream."
            + " strategyOrdinal: " + strategyOrdinal
            + " fpp: " + fpp
            + " size: " + size
            + " checksum: " + checksum
            + " numBuckets: " + numBuckets
            + " numEntriesPerBucket: " + numEntriesPerBucket
            + " numBitsPerEntry: " + numBitsPerEntry
            + " dataLength: " + dataLength);
    ioException.initCause(e);
    throw ioException;
  }
}
 
Example 17
Source File: EphGps.java    From GNSS_Compare with Apache License 2.0 4 votes vote down vote up
@Override
public void read(DataInputStream dai, boolean oldVersion) throws IOException {
	int v=1;
	if(!oldVersion) v=dai.readInt();

	if(v==1){
		long l = dai.readLong();
		refTime = new Time(l>0?l:System.currentTimeMillis());
		satID = dai.read();
		week = dai.readInt();
		L2Code = dai.readInt();
		L2Flag = dai.readInt();
		svAccur = dai.readInt();
		svHealth = dai.readInt();
		iode = dai.readInt();
		iodc = dai.readInt();
		toc = dai.readDouble();
		toe = dai.readDouble();
		af0 = dai.readDouble();
		af1 = dai.readDouble();
		af2 = dai.readDouble();
		tgd = dai.readDouble();
		rootA = dai.readDouble();
		e = dai.readDouble();
		i0 = dai.readDouble();
		iDot = dai.readDouble();
		omega = dai.readDouble();
		omega0 = dai.readDouble();
		omegaDot = dai.readDouble();
		M0 = dai.readDouble();
		deltaN = dai.readDouble();
		crc = dai.readDouble();
		crs = dai.readDouble();
		cuc = dai.readDouble();
		cus = dai.readDouble();
		cic = dai.readDouble();
		cis = dai.readDouble();
		fitInt = dai.readLong();
	}else{
		throw new IOException("Unknown format version:"+v);
	}
}
 
Example 18
Source File: ScanAndClearUnusedResource.java    From ScanUnusedResouce with Apache License 2.0 4 votes vote down vote up
private static void readContantsInClass(InputStream is, StringBuilder sb) throws IOException {
       DataInputStream dis = new DataInputStream(is);
       int magic = 0xCAFEBABE;
       if (!(magic == dis.readInt())) {
           dis.close();
           return;
       }

       dis.readShort(); //minor_version
       dis.readShort();//major_version
       int constant_pool_count = dis.readShort();

/*		常量池中数据项类型		类型标志 	类型描述
           CONSTANT_Utf8				1		UTF-8编码的Unicode字符串
		CONSTANT_Integer			3		int类型字面值
		CONSTANT_Float				4		float类型字面值
		CONSTANT_Long				5		long类型字面值
		CONSTANT_Double				6		double类型字面值
		CONSTANT_Class				7		对一个类或接口的符号引用
		CONSTANT_String	            8		String类型字面值
		CONSTANT_Fieldref			9		对一个字段的符号引用
		CONSTANT_Methodref			10		对一个类中声明的方法的符号引用
		CONSTANT_InterfaceMethodref	11		对一个接口中声明的方法的符号引用
		CONSTANT_NameAndType		12		对一个字段或方法的部分符号引用
 */
       for (int i = 1; i < constant_pool_count; i++) { // 常量池
           int tag = dis.readByte();
           switch (tag) {
               case 1: //CONSTANT_Utf8
                   short len = dis.readShort();
                   if (len < 0) {
                       System.out.println("len " + len);
                       continue;
                   }
                   byte[] bs = new byte[len];
                   dis.read(bs);
                   pln(new String(bs), sb);
                   continue;
               case 3: //CONSTANT_Integer
                   int v_int = dis.readInt();
                   pln(v_int, sb);
                   continue;
               case 4: //CONSTANT_Float
                   float v_float = dis.readFloat();
                   pln(v_float, sb);
                   continue;
               case 5: //CONSTANT_Long
                   long v_long = dis.readLong();
                   pln(v_long, sb);
                   continue;
               case 6: //CONSTANT_Double
                   double v_double = dis.readDouble();
                   pln(v_double, sb);
                   continue;
               case 7: //CONSTANT_String
                   dis.readShort();
                   continue;
               case 8: //CONSTANT_String
                   dis.readShort();
                   continue;
               case 9: //CONSTANT_Fieldref_info
                   dis.readShort(); //指向一个CONSTANT_Class_info数据项
                   dis.readShort(); //指向一个CONSTANT_NameAndType_info
                   continue;
               case 10: //CONSTANT_Methodref_info
                   dis.readShort(); //指向一个CONSTANT_Class_info数据项
                   dis.readShort(); //指向一个CONSTANT_NameAndType_info
                   continue;
               case 11: //CONSTANT_InterfaceMethodref_info
                   dis.readShort(); //指向一个CONSTANT_Class_info数据项
                   dis.readShort(); //指向一个CONSTANT_NameAndType_info
                   continue;
               case 12:
                   dis.readShort();
                   dis.readShort();
                   continue;
               default:
                   return;
           }
       }
   }
 
Example 19
Source File: ArrayUtil.java    From deeplearning4j with Apache License 2.0 4 votes vote down vote up
public static double[] readDouble(int length, DataInputStream dis) throws IOException {
    double[] ret = new double[length];
    for (int i = 0; i < length; i++)
        ret[i] = dis.readDouble();
    return ret;
}
 
Example 20
Source File: BinaryConstantPool.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Constructor
 */
BinaryConstantPool(DataInputStream in) throws IOException {
    // JVM 4.1 ClassFile.constant_pool_count
    types = new byte[in.readUnsignedShort()];
    cpool = new Object[types.length];
    for (int i = 1 ; i < cpool.length ; i++) {
        int j = i;
        // JVM 4.4 cp_info.tag
        switch(types[i] = in.readByte()) {
          case CONSTANT_UTF8:
            cpool[i] = in.readUTF();
            break;

          case CONSTANT_INTEGER:
            cpool[i] = new Integer(in.readInt());
            break;
          case CONSTANT_FLOAT:
            cpool[i] = new Float(in.readFloat());
            break;
          case CONSTANT_LONG:
            cpool[i++] = new Long(in.readLong());
            break;
          case CONSTANT_DOUBLE:
            cpool[i++] = new Double(in.readDouble());
            break;

          case CONSTANT_CLASS:
          case CONSTANT_STRING:
            // JVM 4.4.3 CONSTANT_String_info.string_index
            // or JVM 4.4.1 CONSTANT_Class_info.name_index
            cpool[i] = new Integer(in.readUnsignedShort());
            break;

          case CONSTANT_FIELD:
          case CONSTANT_METHOD:
          case CONSTANT_INTERFACEMETHOD:
          case CONSTANT_NAMEANDTYPE:
            // JVM 4.4.2 CONSTANT_*ref_info.class_index & name_and_type_index
            cpool[i] = new Integer((in.readUnsignedShort() << 16) | in.readUnsignedShort());
            break;

          case CONSTANT_METHODHANDLE:
            cpool[i] = readBytes(in, 3);
            break;
          case CONSTANT_METHODTYPE:
            cpool[i] = readBytes(in, 2);
            break;
          case CONSTANT_INVOKEDYNAMIC:
            cpool[i] = readBytes(in, 4);
            break;

          case 0:
          default:
            throw new ClassFormatError("invalid constant type: " + (int)types[i]);
        }
    }
}