Java Code Examples for java.io.RandomAccessFile#readLong()

The following examples show how to use java.io.RandomAccessFile#readLong() . 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: TestRecordingFile.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static Path createBrokenMetadata(Path valid) throws Exception {
    try {
        Path broken = Utils.createTempFile("broken-metadata", ".jfr");
        Files.delete(broken);
        Files.copy(valid, broken);
        RandomAccessFile raf = new RandomAccessFile(broken.toFile(), "rw");
        raf.seek(METADATA_OFFSET);
        long metadataOffset = raf.readLong();
        raf.seek(metadataOffset);
        raf.writeLong(Long.MAX_VALUE);
        raf.writeLong(Long.MAX_VALUE);
        raf.close();
        return broken;
    } catch (IOException ioe) {
        throw new Exception("Could not produce a broken EventSet from file " + valid, ioe);
    }
}
 
Example 2
Source File: OverlappedTrainingRunner.java    From sgdtk with Apache License 2.0 6 votes vote down vote up
private void passN() throws IOException
{

    // Get FV from file
    randomAccessFile = new RandomAccessFile(getCacheFile(), "r");

    while (randomAccessFile.getFilePointer() < randomAccessFile.length())
    {
        int recordLength = (int) randomAccessFile.readLong();
        packBuffer = growIfNeeded(packBuffer, recordLength);
        randomAccessFile.read(packBuffer, 0, recordLength);
        FeatureVector fv = toFeatureVector();
        // add to ring buffer
        addWithProb(fv);

    }

    randomAccessFile.close();

    signalEndEpoch();

}
 
Example 3
Source File: DiskFPSet.java    From tlaplus with MIT License 6 votes vote down vote up
public long checkFPs() throws IOException {
	// It seems pointless to acquire the locks when checkFPs is only
	// executed after model checking has finished. Lock the disk
	// fingerprint sets though. Acquiring the locks is cheap.
	acquireTblWriteLock();
	flusher.flushTable();
	releaseTblWriteLock();

	RandomAccessFile braf = new BufferedRandomAccessFile(
			this.fpFilename, "r");
	long fileLen = braf.length();
	long dis = Long.MAX_VALUE;
	if (fileLen > 0) {
		long x = braf.readLong();
		while (braf.getFilePointer() < fileLen) {
			long y = braf.readLong();
			long dis1 = y - x;
			if (dis1 >= 0) {
				dis = Math.min(dis, dis1);
			}
			x = y;
		}
	}
	braf.close();
	return dis;
}
 
Example 4
Source File: TestRecordingFile.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static Path createBrokenMetadata(Path valid) throws Exception {
    try {
        Path broken = Utils.createTempFile("broken-metadata", ".jfr");
        Files.delete(broken);
        Files.copy(valid, broken);
        RandomAccessFile raf = new RandomAccessFile(broken.toFile(), "rw");
        raf.seek(METADATA_OFFSET);
        long metadataOffset = raf.readLong();
        raf.seek(metadataOffset);
        raf.writeLong(Long.MAX_VALUE);
        raf.writeLong(Long.MAX_VALUE);
        raf.close();
        return broken;
    } catch (IOException ioe) {
        throw new Exception("Could not produce a broken EventSet from file " + valid, ioe);
    }
}
 
Example 5
Source File: ShortLong.java    From nyzoVerifier with The Unlicense 5 votes vote down vote up
public static ShortLong fromFile(RandomAccessFile file) {
    long combinedValue = 0;
    try {
        combinedValue = file.readLong();
    } catch (Exception ignored) { }
    int shortValue = (int) ((combinedValue >> 48) & 0xffff);
    long longValue = combinedValue & 0xffffffffffffL;
    return new ShortLong(shortValue, longValue);
}
 
Example 6
Source File: Paged.java    From btree4j with Apache License 2.0 5 votes vote down vote up
protected void read(RandomAccessFile raf) throws IOException {
    this._fhSize = raf.readShort();
    this._pageSize = raf.readInt();
    this._totalPageCount = raf.readLong();
    this._firstFreePage = raf.readLong();
    this._lastFreePage = raf.readLong();
    this._pageHeaderSize = raf.readByte();
}
 
Example 7
Source File: OffHeapDiskFPSet.java    From tlaplus with MIT License 5 votes vote down vote up
protected void writeIndex(long[] index, final RandomAccessFile raf, long length) throws IOException {
	for (int i = 0; i < index.length; i++) {
		long pos = Math.min(((long) i) * NumEntriesPerPage, length);
		raf.seek(pos * LongSize);
		final long value = raf.readLong();
		index[i] = value;
	}
}
 
Example 8
Source File: OffHeapDiskFPSet.java    From tlaplus with MIT License 5 votes vote down vote up
private static boolean checkIndex(final long[] idx, final RandomAccessFile raf, final long length) throws IOException {
	for (long i = 0L; i < idx.length; i++) {
		final long pos = Math.min(i * NumEntriesPerPage, length);
		raf.seek(pos * LongSize);
		final long value = raf.readLong();
		final long index = idx[(int) i];
		if (value != index) {
			return false;
		}
	}
	return true;
}
 
Example 9
Source File: Block.java    From nyzoVerifier with The Unlicense 5 votes vote down vote up
public static Block fromFile(RandomAccessFile file) {

        Block block = null;

        try {
            ShortLong versionAndHeight = ShortLong.fromFile(file);
            int blockchainVersion = versionAndHeight.getShortValue();
            long blockHeight = versionAndHeight.getLongValue();
            byte[] previousBlockHash = Message.getByteArray(file, FieldByteSize.hash);
            long startTimestamp = file.readLong();
            long verificationTimestamp = file.readLong();
            int numberOfTransactions = file.readInt();
            List<Transaction> transactions = new ArrayList<>();
            for (int i = 0; i < numberOfTransactions; i++) {
                transactions.add(Transaction.fromFile(file, blockHeight, previousBlockHash, false));
            }

            byte[] balanceListHash = Message.getByteArray(file, FieldByteSize.hash);
            byte[] verifierIdentifier = Message.getByteArray(file, FieldByteSize.identifier);
            byte[] verifierSignature = Message.getByteArray(file, FieldByteSize.signature);

            // Transaction validation only needs to occur on blocks past the frozen edge.
            boolean validateTransactions = false;

            block = new Block(blockchainVersion, blockHeight, previousBlockHash, startTimestamp, verificationTimestamp,
                    transactions, balanceListHash, verifierIdentifier, verifierSignature, validateTransactions);
        } catch (Exception ignored) { }

        return block;
    }
 
Example 10
Source File: AbstractFileCheckpointCollection.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Constructs a new file header for an existing file
 *
 * @param randomAccessFile
 *            the existing file
 * @throws IOException
 *             if an I/O error occurs reading from the file
 */
public CheckpointCollectionFileHeader(RandomAccessFile randomAccessFile) throws IOException {
    fVersion = randomAccessFile.readInt();
    fSize = randomAccessFile.readInt();
    fNbEvents = randomAccessFile.readLong();
    ByteBuffer b = ByteBuffer.allocate(MAX_TIME_RANGE_SERIALIZE_SIZE);
    b.clear();
    fFileChannel.read(b);
    b.flip();
    fTimeRange = new TmfTimeRange(TmfTimestamp.create(b), TmfTimestamp.create(b));
}
 
Example 11
Source File: DiskTreeReader.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Reads the {@link STRtree} object from the file.
 * 
 * @return the quadtree, holding envelops and geometry positions in the file.
 * @throws Exception
 */
public STRtree readIndex() throws Exception {

    File file = new File(path);
    raf = new RandomAccessFile(file, "r");

    raf.seek(6L);
    checkVersions();

    long position = INDEX_ADDRESS_POSITION;
    raf.seek(position);
    long indexAddress = raf.readLong();
    position = INDEX_ADDRESS_POSITION + INDEX_ADDRESS_SIZE;
    raf.seek(position);
    long indexSize = raf.readLong();

    raf.seek(indexAddress);
    byte[] indexBytes = new byte[(int) indexSize];
    int read = raf.read(indexBytes);
    if (read != indexSize) {
        throw new IOException();
    }

    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(indexBytes));
    indexObj = (STRtree) in.readObject();
    return indexObj;
}
 
Example 12
Source File: BTree.java    From btree4j with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void read(RandomAccessFile raf) throws IOException {
    super.read(raf);
    this._duplicateAllowed = raf.readBoolean();
    this._rootPage = raf.readLong();
}
 
Example 13
Source File: ArchiveFile.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
protected void openArchiveForAppending( ) throws IOException
{
	// we need upgrade the document
	RandomAccessFile rf = new RandomAccessFile( archiveName, "rw" );
	if ( rf.length( ) == 0 )
	{
		// this is a empty file
		af = new ArchiveFileV3( archiveName, rf, "rw" );
	}
	else
	{
		try
		{
			long magicTag = rf.readLong( );
			if ( magicTag == ARCHIVE_V2_TAG )
			{
				af = new ArchiveFileV2( archiveName, rf, "rw+" );
			}
			else if ( magicTag == ARCHIVE_V3_TAG )
			{
				af = new ArchiveFileV3( archiveName, rf, "rw+" );
			}
			else if ( isZipFile( magicTag ) )
			{
				rf.close( );
				zipOnClose = true;
				tmpFileName = getTmpFileName( );
				unzip( archiveName, tmpFileName );
				ArchiveFileV3 fs = new ArchiveFileV3( tmpFileName, "rw+" );
				af = fs;
			}
			else
			{
				rf.close( );
				upgradeArchiveV1( );
				af = new ArchiveFileV3( archiveName, "rw+" );
			}
			upgradeSystemId( af );
		}
		catch ( IOException ex )
		{
			rf.close( );
			throw ex;
		}
	}
}
 
Example 14
Source File: DiskFPSet.java    From tlaplus with MIT License 4 votes vote down vote up
public void recover(String fname) throws IOException {
	RandomAccessFile chkptRAF = new BufferedRandomAccessFile(
			this.getChkptName(fname, "chkpt"), "r");
	RandomAccessFile currRAF = new BufferedRandomAccessFile(
			this.fpFilename, "rw");

	this.fileCnt = chkptRAF.length() / LongSize;
	int indexLen = (int) ((this.fileCnt - 1) / NumEntriesPerPage) + 2;
	this.index = new long[indexLen];
	this.currIndex = 0;
	this.counter = 0;

	long fp = 0L;
	try {
		long predecessor = Long.MIN_VALUE;
		while (true) {
			fp = chkptRAF.readLong();
			this.writeFP(currRAF, fp);
			// check invariant
			Assert.check(predecessor < fp, EC.SYSTEM_INDEX_ERROR);
			predecessor = fp;
		}
	} catch (EOFException e) {
		Assert.check(this.currIndex == indexLen - 1, EC.SYSTEM_INDEX_ERROR);
		this.index[indexLen - 1] = fp;
	}

	chkptRAF.close();
	currRAF.close();

	// reopen a BufferedRAF for each thread
	for (int i = 0; i < this.braf.length; i++) {
		// Better way would be to provide method BRAF.open
		// close and reopen
		this.braf[i].close();
		this.braf[i] = new BufferedRandomAccessFile(this.fpFilename,
				"r");
	}
	for (int i = 0; i < this.brafPool.length; i++) {
		// Better way would be to provide method BRAF.open
		// close and reopen
		this.brafPool[i].close();
		this.brafPool[i] = new BufferedRandomAccessFile(
				this.fpFilename, "r");
	}
	this.poolIndex = 0;
}
 
Example 15
Source File: BTree.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
private BTreeHeader(RandomAccessFile randomAccessFile) throws IOException {
    super(randomAccessFile);

    fRoot = randomAccessFile.readLong();
    fSubVersion = randomAccessFile.readInt();
}
 
Example 16
Source File: BPlusTree.java    From BPlusTree with Apache License 2.0 4 votes vote down vote up
/**
 * Reads an existing file and generates a B+ configuration based on the stored values
 *
 * @param r file to read from
 * @param generateConf generate configuration?
 * @return new configuration based on read values (if enabled) or null
 * @throws IOException is thrown when an I/O operation fails
 * @throws InvalidBTreeStateException is thrown when there are inconsistencies in the blocks.
 */
private BPlusConfiguration readFileHeader(RandomAccessFile r, boolean generateConf)
        throws IOException, InvalidBTreeStateException {
    r.seek(0L);

    // read the header number
    int headerNumber = r.readInt();

    if(headerNumber < 0)
        {throw new InvalidBTreeStateException("Negative header number found...");}

    // read the page size
    int pageSize = r.readInt();

    if(pageSize < 0)
        {throw new InvalidBTreeStateException("Cannot create a tree with negative page size");}

    // read the entry size
    int entrySize = r.readInt();

    if(entrySize <= 0)
        {throw new InvalidBTreeStateException("Entry size must be > 0");}

    // key size
    int keySize = r.readInt();

    if(keySize > 8 || keySize < 4)
        {throw new InvalidBTreeStateException("Key size but be either 4 or 8 bytes");}

    // read the number of pages (excluding the lookup)
    totalTreePages = r.readLong();

    if(totalTreePages < 0)
        {throw new InvalidBTreeStateException("Tree page number cannot be < 0");}


    // read the max page offset
    maxPageNumber = r.readLong();

    if(maxPageNumber < 0 || (totalTreePages > 0 && maxPageNumber == 0))
        {throw new InvalidBTreeStateException("Invalid max page offset");}

    // read the root index
    long rootIndex = r.readLong();

    if(rootIndex < 0)
        {throw new InvalidBTreeStateException("Root can't have index < 0");}

    // read the next lookup page pointer
    this.firstPoolNextPointer = r.readLong();

    // read the root.
    root = readNode(rootIndex);
    // finally if needed create a configuration file
    if(generateConf)
        {return(new BPlusConfiguration(pageSize, keySize, entrySize));}
    else
        {return(null);}
}
 
Example 17
Source File: GEMFFile.java    From osmdroid with Apache License 2.0 4 votes vote down vote up
private void readHeader() throws IOException {
	final RandomAccessFile baseFile = mFiles.get(0);

	// Get file sizes
	for (final RandomAccessFile file : mFiles) {
		mFileSizes.add(file.length());
	}

	// Version
	final int version = baseFile.readInt();
	if (version != VERSION) {
		throw new IOException("Bad file version: " + version);
	}

	// Tile Size
	final int tile_size = baseFile.readInt();
	if (tile_size != TILE_SIZE) {
		throw new IOException("Bad tile size: " + tile_size);
	}

	// Read Source List
	final int sourceCount = baseFile.readInt();

	for (int i=0;i<sourceCount;i++) {
		final int sourceIndex = baseFile.readInt();
		final int sourceNameLength = baseFile.readInt();
		final byte[] nameData = new byte[sourceNameLength];
		baseFile.read(nameData, 0, sourceNameLength);

		final String sourceName = new String(nameData);
		mSources.put(new Integer(sourceIndex), sourceName);
	}

	// Read Ranges
	final int num_ranges = baseFile.readInt();
	for (int i=0;i<num_ranges;i++) {
		final GEMFRange rs = new GEMFRange();
		rs.zoom = baseFile.readInt();
		rs.xMin = baseFile.readInt();
		rs.xMax = baseFile.readInt();
		rs.yMin = baseFile.readInt();
		rs.yMax = baseFile.readInt();
		rs.sourceIndex = baseFile.readInt();
		rs.offset = baseFile.readLong();
		mRangeData.add(rs);
	}
}
 
Example 18
Source File: Lobstack.java    From jelectrum with MIT License 4 votes vote down vote up
public Lobstack(File dir, String name, boolean compress, int key_step_size)
  throws IOException
{
  this.key_step_size  = key_step_size;
  this.dir = dir;
  this.stack_name = name;
  this.compress = compress;

  if (!dir.exists())
  {
    throw new java.io.IOException("Directory does not exist: " + dir);
  }
  if (!dir.isDirectory())
  {
    throw new java.io.IOException("Location is not a directory: " + dir);
  }

  data_files = new AutoCloseLRUCache<Long, FileChannel>(MAX_OPEN_FILES);

  RandomAccessFile root_file = new RandomAccessFile(new File(dir, name + ".root"), MODE);

  root_file_channel = root_file.getChannel();

  if (root_file.length()==0)
  {
    root_file.setLength(16);
    reset();
  }
  else
  {
    synchronized(ptr_lock)
    {
      root_file.seek(ROOT_ROOT_LOCATION);
      current_root = root_file.readLong();
      root_file.seek(ROOT_WRITE_LOCATION);
      current_write_location = root_file.readLong();
    }
  }
 
  showSize();

}
 
Example 19
Source File: FeatureVector.java    From sgdtk with Apache License 2.0 3 votes vote down vote up
/**
 * Read a dense vector in from a file.  Working memory will be allocated underneath.  Note that, for this reason,
 * OverlappedTrainingRunner does not use this memory, but instead uses a pre-allocated work buffer, which is resized
 * as necessary
 *
 * @param input A file
 * @return
 * @throws IOException
 */
public static FeatureVector deserializeDenseFrom(RandomAccessFile input) throws IOException
{
    int sz = (int)input.readLong();
    byte[] b = new byte[sz];
    input.read(b, 0, sz);
    FeatureVector fv = deserializeDense(b);
    return fv;
}
 
Example 20
Source File: FeatureVector.java    From sgdtk with Apache License 2.0 3 votes vote down vote up
/**
 * Read a sparse vector in from a file.  Working memory will be allocated underneath.  Note that, for this reason,
 * OverlappedTrainingRunner does not use this memory, but instead uses a pre-allocated work buffer, which is resized
 * as necessary
 *
 * @param input A file
 * @return
 * @throws IOException
 */
public static FeatureVector deserializeSparseFrom(RandomAccessFile input) throws IOException
{
    int sz = (int)input.readLong();
    byte[] b = new byte[sz];
    input.read(b, 0, sz);
    FeatureVector fv = deserializeSparse(b);
    return fv;
}