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

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

源代码1 项目: localization_nifi   文件: FileSystemSwapManager.java
private SwapDeserializer createSwapDeserializer(final DataInputStream dis) throws IOException {
    dis.mark(MAGIC_HEADER.length);

    final byte[] magicHeader = new byte[MAGIC_HEADER.length];
    try {
        StreamUtils.fillBuffer(dis, magicHeader);
    } catch (final EOFException eof) {
        throw new IOException("Failed to read swap file because the file contained less than 4 bytes of data");
    }

    if (Arrays.equals(magicHeader, MAGIC_HEADER)) {
        final String serializationName = dis.readUTF();
        if (serializationName.equals(SchemaSwapDeserializer.getSerializationName())) {
            return new SchemaSwapDeserializer();
        }

        throw new IOException("Cannot find a suitable Deserializer for swap file, written with Serialization Name '" + serializationName + "'");
    } else {
        // SimpleSwapDeserializer is old and did not write out a magic header.
        dis.reset();
        return new SimpleSwapDeserializer();
    }
}
 
源代码2 项目: hbase   文件: RegionInfo.java
/**
 * Parses an RegionInfo instance from the passed in stream.
 * Presumes the RegionInfo was serialized to the stream with
 * {@link #toDelimitedByteArray(RegionInfo)}.
 * @return An instance of RegionInfo.
 */
static RegionInfo parseFrom(final DataInputStream in) throws IOException {
  // I need to be able to move back in the stream if this is not a pb
  // serialization so I can do the Writable decoding instead.
  int pblen = ProtobufUtil.lengthOfPBMagic();
  byte [] pbuf = new byte[pblen];
  if (in.markSupported()) { //read it with mark()
    in.mark(pblen);
  }

  //assumption: if Writable serialization, it should be longer than pblen.
  int read = in.read(pbuf);
  if (read != pblen) throw new IOException("read=" + read + ", wanted=" + pblen);
  if (ProtobufUtil.isPBMagicPrefix(pbuf)) {
    return ProtobufUtil.toRegionInfo(HBaseProtos.RegionInfo.parseDelimitedFrom(in));
  } else {
    throw new IOException("PB encoded RegionInfo expected");
  }
}
 
源代码3 项目: RDFS   文件: EditLogFileInputStream.java
/**
 * Read the header of fsedit log
 * @param in fsedit stream
 * @return the edit log version number
 * @throws IOException if error occurs
 */
static int readLogVersion(DataInputStream in) throws IOException,
    LogHeaderCorruptException {
  int logVersion = 0;
  // Read log file version. Could be missing.
  in.mark(4);
  // If edits log is greater than 2G, available method will return negative
  // numbers, so we avoid having to call available
  boolean available = true;
  try {
    logVersion = in.readByte();
  } catch (EOFException e) {
    available = false;
  }

  if (available) {
    in.reset();
    logVersion = in.readInt();
    if (logVersion < FSConstants.LAYOUT_VERSION) { // future version
      throw new LogHeaderCorruptException(
          "Unexpected version of the file system log file: " + logVersion
              + ". Current version = " + FSConstants.LAYOUT_VERSION + ".");
    }
  }
  return logVersion;
}
 
源代码4 项目: nifi   文件: FileSystemSwapManager.java
private SwapDeserializer createSwapDeserializer(final DataInputStream dis) throws IOException {
    dis.mark(MAGIC_HEADER.length);

    final byte[] magicHeader = new byte[MAGIC_HEADER.length];
    try {
        StreamUtils.fillBuffer(dis, magicHeader);
    } catch (final EOFException eof) {
        throw new IOException("Failed to read swap file because the file contained less than 4 bytes of data");
    }

    if (Arrays.equals(magicHeader, MAGIC_HEADER)) {
        final String serializationName = dis.readUTF();
        if (serializationName.equals(SchemaSwapDeserializer.getSerializationName())) {
            return new SchemaSwapDeserializer();
        }

        throw new IOException("Cannot find a suitable Deserializer for swap file, written with Serialization Name '" + serializationName + "'");
    } else {
        // SimpleSwapDeserializer is old and did not write out a magic header.
        dis.reset();
        return new SimpleSwapDeserializer();
    }
}
 
@Override
public MessageStoreSerializer newInstance(final DataInputStream data) throws IOException
{

    // All encodings should start 0x00 << int length of the version string>> << version string in UTF-8 >>
    data.mark(50);
    if (data.read() != 0)
    {
        throw new IllegalArgumentException("Invalid format for upload");
    }
    int stringLength = data.readInt();
    byte[] stringBytes = new byte[stringLength];
    data.readFully(stringBytes);

    String version = new String(stringBytes, StandardCharsets.UTF_8);

    data.reset();

    Map<String, MessageStoreSerializer> serializerMap =
            new QpidServiceLoader().getInstancesByType(MessageStoreSerializer.class);

    MessageStoreSerializer serializer = serializerMap.get(version);

    if(serializer == null)
    {
        throw new IllegalArgumentException("Message store import uses version '"
                                           + version + "' which is not supported");
    }
    else
    {
        return serializer;
    }
}
 
源代码6 项目: AIBot   文件: CompressedStreamTools.java
public static CompressionType detectType(InputStream is) throws IOException{		
	DataInputStream in = new DataInputStream(is);
	
	if(in.markSupported())
		in.mark(256);
	
	byte firstByte = in.readByte();
	CompressionType type;
	switch(firstByte){
	case -1:
		throw new EOFException();
	case 0x0a: //NBT Compund tag identifier
		type = CompressionType.NONE;
		break;
	case 0x1F: //GZip magic number
		type = CompressionType.GZIP;
		break;
	case 0x78: //ZLib header
		type = CompressionType.ZLIB;
		break;
	default:
		throw new InvalidParameterException("Could not auto detect the compression format.");
	}
	if(in.markSupported())
		in.reset();
	return type;
}
 
源代码7 项目: antsdb   文件: JdbcRestoreMain.java
public void restoreContent(DataInputStream din, TableBackupInfo table, boolean pass) throws Exception {
    din.readUTF();
    Supplier<Object[]> rowReader = ()-> {
        try {
            din.mark(4);
            if (din.readInt() == 0) {
                return null;
            }
            din.reset();
            Object[] row = new Object[table.columns.length];
            for (int i=0; i<table.columns.length; i++) {
                row[i] = readValue(din);
            }
            return row;
        }
        catch (Exception x) {
            throw new RuntimeException(x);
        }
    };
    if (pass) {
        skipContent(table, rowReader);
    }
    else {
        long count = restoreContent(table, rowReader);
        println(" " + count + " rows");
    }
}
 
源代码8 项目: sketch   文件: ExifInterface.java
public ByteOrderedDataInputStream(InputStream in) throws IOException {
    mInputStream = in;
    mDataInputStream = new DataInputStream(in);
    mLength = mDataInputStream.available();
    mPosition = 0;
    mDataInputStream.mark(mLength);
}
 
源代码9 项目: computoser   文件: SMFTools.java
/**
 * Reads a MIDI track chunk
 *
 * @param DataInputStream
 *            dis - the input stream to read from
 * @exception IOException
 */
private void readTrackChunk(DataInputStream dis) throws IOException {
    // local variables for Track class
    Track track = new Track();
    // Insert new Track into a list of tracks
    this.trackList.addElement(track);
    int deltaTime = 0;
    // Read track header
    if (dis.readInt() != 0x4D54726B) {// If MTrk read is wrong
        throw new IOException("Track started in wrong place!!!!  ABORTING");
    } else {// If MTrk read ok get bytesRemaining
        dis.readInt();
    }
    // loop variables
    int status, oldStatus = 0, eventLength = 0;
    // Start gathering event data
    Event event = null;
    while (true) {
        try {
            // get variable length timestamp
            deltaTime = MidiUtil.readVarLength(dis);
            // mark stream so we can return if we need running status
            dis.mark(2);
            status = dis.readUnsignedByte();
            // decide on running status
            if (status < 0x80) { // set running status
                status = oldStatus;
                // return stream to before status read
                dis.reset();
            }
            // create default event of correct type
            if (status >= 0xFF) { // Meta Event
                int type = dis.readUnsignedByte();
                eventLength = MidiUtil.readVarLength(dis);
                event = jm.midi.MidiUtil.createMetaEvent(type);
            } else if (status >= 0xF0) { // System Exclusive --- NOT
                                         // SUPPORTED
                eventLength = MidiUtil.readVarLength(dis);
            } else if (status >= 0x80) { // MIDI voice event
                short selection = (short) (status / 0x10);
                short midiChannel = (short) (status - (selection * 0x10));
                VoiceEvt evt = (VoiceEvt) MidiUtil.createVoiceEvent(selection);
                if (evt == null) {
                    throw new IOException("MIDI file read error: invalid voice event type!");
                }
                evt.setMidiChannel(midiChannel);
                event = evt;
            }
            oldStatus = status;
        } catch (EOFException ex) {
            logger.warn("EOFException (" + ex.getMessage() + ") encountered in SMFTools");
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
        if (event != null) {
            // read data into the new event and
            // add the new event to the Track object
            event.setTime(deltaTime);
            event.read(dis);
            track.addEvent(event);
            // event.print();
            if (event instanceof EndTrack)
                break;
        } else {
            // skip the stream ahead to next valid event
            dis.skipBytes(eventLength);
        }
    }
}
 
源代码10 项目: jmg   文件: RTMidiIn.java
/**
 * Called from the JavaSound MIDI Input Port for each new MIDI event
 */
public void send(MidiMessage message, long deltaTime){
	System.out.println("New MIDI message");
	Event event = null;
	ByteArrayInputStream bais=new ByteArrayInputStream(message.getMessage());
	DataInputStream dis = new DataInputStream(bais);
	try{
		dis.mark(2);
		int status = dis.readUnsignedByte();
		int length = 0;
		//check running status
		if(status < 0x80){
			status = oldStatus;
			dis.reset();
		}
		if(status >= 0xFF){//MetaEvent
			int type = dis.readUnsignedByte();
			length = MidiUtil.readVarLength(dis);
			event = MidiUtil.createMetaEvent(type);
		}else if(status >= 0xF0){ //System Exclusive -- Not Supported
			System.out.println("SysEX---");
			length = MidiUtil.readVarLength(dis);
		}else if(status >= 0x80){ //MIDI voice event
			short selection = (short) (status /0x10);
			short midiChannel = (short) (status - (selection * 0x10));
			VoiceEvt evt = (VoiceEvt)MidiUtil.createVoiceEvent(selection);
			evt.setMidiChannel(midiChannel);
			event = evt;
			if(event == null){
				throw new IOException("Read Error");
			}
		}
		if(event != null){
			event.setTime((int)deltaTime);
			event.read(dis);
		}
		oldStatus = status;
	}catch(Exception e){
		e.printStackTrace();
		System.exit(1);
	}
	this.notifyListeners(event);
}
 
源代码11 项目: jmg   文件: SMF.java
/**
 * Reads a MIDI track chunk
 * @param DataInputStream dis - the input stream to read from
 * @exception IOException
 */
private void readTrackChunk(DataInputStream dis) 
           throws IOException{
           //local variables for Track class
           Track track = new Track();
           //Insert new Track into a list of tracks
           this.trackList.addElement(track);  
           int deltaTime = 0;
           if(VERBOSE) System.out.println("Reading Track ..........");
           //Read track header
           if(dis.readInt() != 0x4D54726B){//If MTrk read is wrong
                   throw new IOException
                           ("Track started in wrong place!!!!  ABORTING");
           }else{//If MTrk read ok get bytesRemaining
                   dis.readInt();
           }
           //loop variables
           int status, oldStatus =0, eventLength = 0;
           //Start gathering event data
           Event event = null;
           while(true){
               try{
                   //get variable length timestamp
                   deltaTime = MidiUtil.readVarLength(dis); 
                   //mark stream so we can return if we need running status
                   dis.mark(2);
                   status = dis.readUnsignedByte();
                   //decide on running status
                   if(status < 0x80){ //set running status
                       status = oldStatus;
                       //return stream to before status read
                       dis.reset();
                   }
                   //create default event of correct type
                   if(status >= 0xFF){ //Meta Event
                       int type = dis.readUnsignedByte(); 
                       eventLength = MidiUtil.readVarLength(dis);
                       event = MidiUtil.createMetaEvent(type); 
                   }else if(status >= 0xF0){ //System Exclusive --- NOT SUPPORTED
                       System.out.println("SysEX---");
                       eventLength = MidiUtil.readVarLength( dis);
                   }else if(status >= 0x80){ //MIDI voice event 
                       short selection = (short) (status / 0x10);
                       short midiChannel = (short) (status - (selection * 0x10));
                       VoiceEvt evt = (VoiceEvt)MidiUtil.createVoiceEvent(selection);
                       evt.setMidiChannel(midiChannel);
                       event = evt;
                       if(event == null){
                          throw new IOException("MIDI file read error: invalid voice event type!");
                       }
                   }
                   oldStatus = status;
               }catch(Exception e){
                   e.printStackTrace();
                   System.exit(1);
               }   
               if(event != null){
                   //read data into the new event and
                   //add the new event to the Track object
                   event.setTime(deltaTime);
                   event.read(dis);
                   //if (VERBOSE) event.print();
                   track.addEvent(event);
                   //event.print();
                   if(event instanceof EndTrack)
                           break;
               }else{
                   //skip the stream ahead to next valid event
                   dis.skipBytes(eventLength);
               }	
           }
}
 
源代码12 项目: hadoop   文件: OfflineImageViewer.java
/**
 * Check an fsimage datainputstream's version number.
 *
 * The datainput stream is returned at the same point as it was passed in;
 * this method has no effect on the datainputstream's read pointer.
 *
 * @param in Datainputstream of fsimage
 * @return Filesystem layout version of fsimage represented by stream
 * @throws IOException If problem reading from in
 */
private int findImageVersion(DataInputStream in) throws IOException {
  in.mark(42); // arbitrary amount, resetting immediately

  int version = in.readInt();
  in.reset();

  return version;
}
 
源代码13 项目: big-c   文件: OfflineImageViewer.java
/**
 * Check an fsimage datainputstream's version number.
 *
 * The datainput stream is returned at the same point as it was passed in;
 * this method has no effect on the datainputstream's read pointer.
 *
 * @param in Datainputstream of fsimage
 * @return Filesystem layout version of fsimage represented by stream
 * @throws IOException If problem reading from in
 */
private int findImageVersion(DataInputStream in) throws IOException {
  in.mark(42); // arbitrary amount, resetting immediately

  int version = in.readInt();
  in.reset();

  return version;
}
 
源代码14 项目: RDFS   文件: OfflineImageViewer.java
/**
 * Check an fsimage datainputstream's version number.
 *
 * The datainput stream is returned at the same point as it was passed in;
 * this method has no effect on the datainputstream's read pointer.
 *
 * @param in Datainputstream of fsimage
 * @return Filesystem layout version of fsimage represented by stream
 * @throws IOException If problem reading from in
 */
private int findImageVersion(DataInputStream in) throws IOException {
  in.mark(42); // arbitrary amount, resetting immediately

  int version = in.readInt();
  in.reset();

  return version;
}