Java Code Examples for java.io.RandomAccessFile.seek()

The following are Jave code examples for showing how to use seek() of the java.io.RandomAccessFile class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: sumo   File: Sentinel1SLCDebursted.java   Source Code and License Vote up 7 votes
@Override
 public void preloadLineTile(int y, int length,int band) {
     if (y < 0) {
         return;
     }
     preloadedInterval = new int[]{y, y + length};
     //positioning in file images y=rows image.xSize=cols 4=numero bytes 
     int tileOffset =  (y * (getImage(band).getxSize() * 4 ));
     preloadedData = new byte[(getImage(band).getxSize() * 4) * length];
     try {
     	File fimg = getImage(band).getImageFile();
fss = new RandomAccessFile(fimg.getAbsolutePath(), "r");
fss.seek(tileOffset);
        	fss.read(preloadedData);
     } catch (IOException ex) {
     	logger.error(ex.getMessage(),ex);
     }finally{
     	try {
	fss.close();
} catch (IOException e) {
	logger.warn(e.getMessage());
}
     }
 }
 
Example 2
Project: Reer   File: LockStateAccess.java   Source Code and License Vote up 6 votes
public LockState readState(RandomAccessFile lockFileAccess) throws IOException {
    try {
        byte[] buffer = new byte[stateRegionSize];
        lockFileAccess.seek(REGION_START);

        int readPos = 0;
        while (readPos < buffer.length) {
            int nread = lockFileAccess.read(buffer, readPos, buffer.length - readPos);
            if (nread < 0) {
                break;
            }
            readPos += nread;
        }

        ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer, 0, readPos);
        DataInputStream dataInput = new DataInputStream(inputStream);

        byte protocolVersion = dataInput.readByte();
        if (protocolVersion != protocol.getVersion()) {
            throw new IllegalStateException(String.format("Unexpected lock protocol found in lock file. Expected %s, found %s.", protocol.getVersion(), protocolVersion));
        }
        return protocol.read(dataInput);
    } catch (EOFException e) {
        return protocol.createInitialState();
    }
}
 
Example 3
Project: openaudible   File: OggFileReader.java   Source Code and License Vote up 6 votes
/**
 * Summarizes the first five pages, normally all we are interested in
 *
 * @param oggFile
 * @throws CannotReadException
 * @throws IOException
 */
public void shortSummarizeOggPageHeaders(File oggFile) throws CannotReadException, IOException {
    RandomAccessFile raf = new RandomAccessFile(oggFile, "r");

    int i = 0;
    while (raf.getFilePointer() < raf.length()) {
        System.out.println("pageHeader starts at absolute file position:" + raf.getFilePointer());
        OggPageHeader pageHeader = OggPageHeader.read(raf);
        System.out.println("pageHeader finishes at absolute file position:" + raf.getFilePointer());
        System.out.println(pageHeader + "\n");
        raf.seek(raf.getFilePointer() + pageHeader.getPageLength());
        i++;
        if (i >= 5) {
            break;
        }
    }
    System.out.println("Raf File Pointer at:" + raf.getFilePointer() + "File Size is:" + raf.length());
    raf.close();
}
 
Example 4
Project: SlotNSlot_Android   File: ZipResourceFile.java   Source Code and License Vote up 6 votes
public void setOffsetFromFile(RandomAccessFile f, ByteBuffer buf) throws IOException {
    long localHdrOffset = mLocalHdrOffset;
    try {
        f.seek(localHdrOffset);
        f.readFully(buf.array());
        if (buf.getInt(0) != kLFHSignature) {
            Log.w(LOG_TAG, "didn't find signature at start of lfh");
            throw new IOException();
        }
        int nameLen = buf.getShort(kLFHNameLen) & 0xFFFF;
        int extraLen = buf.getShort(kLFHExtraLen) & 0xFFFF;
        mOffset = localHdrOffset + kLFHLen + nameLen + extraLen;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}
 
Example 5
Project: incubator-netbeans   File: LongBuffer.java   Source Code and License Vote up 6 votes
LongBuffer revertBuffer() throws IOException {
    LongBuffer reverted = new LongBuffer(buffer.length);
    
    if (bufferSize < buffer.length) {
        for (int i=0;i<bufferSize;i++) {
            reverted.writeLong(buffer[bufferSize - 1 - i]);
        }
    } else {
        writeStream.flush();
        RandomAccessFile raf = new RandomAccessFile(backingFile,"r");
        long offset = raf.length();
        while(offset > 0) {
            offset-=8;
            raf.seek(offset);
            reverted.writeLong(raf.readLong());
        }
    }
    reverted.startReading();
    return reverted;
}
 
Example 6
Project: airgram   File: FileDataSource.java   Source Code and License Vote up 6 votes
@Override
public long open(DataSpec dataSpec) throws FileDataSourceException {
  try {
    uriString = dataSpec.uri.toString();
    file = new RandomAccessFile(dataSpec.uri.getPath(), "r");
    file.seek(dataSpec.position);
    bytesRemaining = dataSpec.length == C.LENGTH_UNBOUNDED ? file.length() - dataSpec.position
        : dataSpec.length;
    if (bytesRemaining < 0) {
      throw new EOFException();
    }
  } catch (IOException e) {
    throw new FileDataSourceException(e);
  }

  opened = true;
  if (listener != null) {
    listener.onTransferStart();
  }

  return bytesRemaining;
}
 
Example 7
Project: ZooKeeper   File: Util.java   Source Code and License Vote up 5 votes
/**
 * Verifies that the file is a valid snapshot. Snapshot may be invalid if 
 * it's incomplete as in a situation when the server dies while in the process
 * of storing a snapshot. Any file that is not a snapshot is also 
 * an invalid snapshot. 
 * 
 * @param f file to verify
 * @return true if the snapshot is valid
 * @throws IOException
 */
public static boolean isValidSnapshot(File f) throws IOException {
    if (f==null || Util.getZxidFromName(f.getName(), "snapshot") == -1)
        return false;

    // Check for a valid snapshot
    RandomAccessFile raf = new RandomAccessFile(f, "r");
    try {
        // including the header and the last / bytes
        // the snapshot should be atleast 10 bytes
        if (raf.length() < 10) {
            return false;
        }
        raf.seek(raf.length() - 5);
        byte bytes[] = new byte[5];
        int readlen = 0;
        int l;
        while(readlen < 5 &&
              (l = raf.read(bytes, readlen, bytes.length - readlen)) >= 0) {
            readlen += l;
        }
        if (readlen != bytes.length) {
            LOG.info("Invalid snapshot " + f
                    + " too short, len = " + readlen);
            return false;
        }
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        int len = bb.getInt();
        byte b = bb.get();
        if (len != 1 || b != '/') {
            LOG.info("Invalid snapshot " + f + " len = " + len
                    + " byte = " + (b & 0xff));
            return false;
        }
    } finally {
        raf.close();
    }

    return true;
}
 
Example 8
Project: update-master   File: UpdateDownloader.java   Source Code and License Vote up 5 votes
private int copy(InputStream in, RandomAccessFile out) throws IOException, UpdateError {

        byte[] buffer = new byte[BUFFER_SIZE];
        BufferedInputStream bis = new BufferedInputStream(in, BUFFER_SIZE);
        try {

            out.seek(out.length());

            int bytes = 0;
            long previousBlockTime = -1;

            while (!isCancelled()) {
                int n = bis.read(buffer, 0, BUFFER_SIZE);
                if (n == -1) {
                    break;
                }
                out.write(buffer, 0, n);
                bytes += n;

                checkNetwork();

                if (mSpeed != 0) {
                    previousBlockTime = -1;
                } else if (previousBlockTime == -1) {
                    previousBlockTime = System.currentTimeMillis();
                } else if ((System.currentTimeMillis() - previousBlockTime) > TIME_OUT) {
                    throw new UpdateError(UpdateError.DOWNLOAD_NETWORK_TIMEOUT);
                }
            }
            return bytes;
        } finally {
            out.close();
            bis.close();
            in.close();
        }
    }
 
Example 9
Project: app-logbrowser   File: LogFileHandler.java   Source Code and License Vote up 5 votes
private int readByte( final RandomAccessFile file, final long position )
{
    try
    {
        file.seek( position );
        return file.readByte();
    }
    catch ( IOException e )
    {
        return -1;
    }
}
 
Example 10
Project: Reer   File: LockInfoAccess.java   Source Code and License Vote up 5 votes
public LockInfo readLockInfo(RandomAccessFile lockFileAccess) throws IOException {
    if (lockFileAccess.length() <= infoRegionPos) {
        return new LockInfo();
    } else {
        lockFileAccess.seek(infoRegionPos);

        DataInputStream inputStream = new DataInputStream(new BufferedInputStream(new RandomAccessFileInputStream(lockFileAccess)));
        byte protocolVersion = inputStream.readByte();
        if (protocolVersion != lockInfoSerializer.getVersion()) {
            throw new IllegalStateException(String.format("Unexpected lock protocol found in lock file. Expected %s, found %s.", lockInfoSerializer.getVersion(), protocolVersion));
        }

        return lockInfoSerializer.read(inputStream);
    }
}
 
Example 11
Project: flume-release-1.7.0   File: TestFileChannelRestart.java   Source Code and License Vote up 5 votes
private void doTestBadCheckpointVersion(boolean backup) throws Exception {
  Map<String, String> overrides = Maps.newHashMap();
  overrides.put(FileChannelConfiguration.USE_DUAL_CHECKPOINTS, String.valueOf(backup));
  channel = createFileChannel(overrides);
  channel.start();
  Assert.assertTrue(channel.isOpen());
  Set<String> in = putEvents(channel, "restart", 10, 100);
  Assert.assertEquals(100, in.size());
  forceCheckpoint(channel);
  if (backup) {
    Thread.sleep(2000);
  }
  channel.stop();
  File checkpoint = new File(checkpointDir, "checkpoint");
  RandomAccessFile writer = new RandomAccessFile(checkpoint, "rw");
  writer.seek(EventQueueBackingStoreFile.INDEX_VERSION *
              Serialization.SIZE_OF_LONG);
  writer.writeLong(2L);
  writer.getFD().sync();
  writer.close();
  channel = createFileChannel(overrides);
  channel.start();
  Assert.assertTrue(channel.isOpen());
  Assert.assertTrue(!backup || channel.checkpointBackupRestored());
  Set<String> out = consumeChannel(channel);
  compareInputAndOut(in, out);
}
 
Example 12
Project: hadoop   File: TestFSEditLogLoader.java   Source Code and License Vote up 5 votes
@Test
public void testValidateEditLogWithCorruptHeader() throws IOException {
  File testDir = new File(TEST_DIR, "testValidateEditLogWithCorruptHeader");
  SortedMap<Long, Long> offsetToTxId = Maps.newTreeMap();
  File logFile = prepareUnfinalizedTestEditLog(testDir, 2, offsetToTxId);
  RandomAccessFile rwf = new RandomAccessFile(logFile, "rw");
  try {
    rwf.seek(0);
    rwf.writeLong(42); // corrupt header
  } finally {
    rwf.close();
  }
  EditLogValidation validation = EditLogFileInputStream.validateEditLog(logFile);
  assertTrue(validation.hasCorruptHeader());
}
 
Example 13
Project: letv   File: ApkExternalInfoTool.java   Source Code and License Vote up 5 votes
private static byte[] a(RandomAccessFile randomAccessFile) throws IOException {
    int i = 1;
    long length = randomAccessFile.length() - 22;
    randomAccessFile.seek(length);
    byte[] bytes = a.getBytes();
    byte read = randomAccessFile.read();
    while (read != (byte) -1) {
        if (read == bytes[0] && randomAccessFile.read() == bytes[1] && randomAccessFile.read() == bytes[2] && randomAccessFile.read() == bytes[3]) {
            break;
        }
        length--;
        randomAccessFile.seek(length);
        read = randomAccessFile.read();
    }
    i = 0;
    if (i == 0) {
        throw new ZipException("archive is not a ZIP archive");
    }
    randomAccessFile.seek((16 + length) + 4);
    byte[] bArr = new byte[2];
    randomAccessFile.readFully(bArr);
    i = new ZipShort(bArr).getValue();
    if (i == 0) {
        return null;
    }
    bArr = new byte[i];
    randomAccessFile.read(bArr);
    return bArr;
}
 
Example 14
Project: hadoop   File: TestIOUtils.java   Source Code and License Vote up 5 votes
@Test
public void testWriteFully() throws IOException {
  final int INPUT_BUFFER_LEN = 10000;
  final int HALFWAY = 1 + (INPUT_BUFFER_LEN / 2);
  byte[] input = new byte[INPUT_BUFFER_LEN];
  for (int i = 0; i < input.length; i++) {
    input[i] = (byte)(i & 0xff);
  }
  byte[] output = new byte[input.length];
  
  try {
    RandomAccessFile raf = new RandomAccessFile(TEST_FILE_NAME, "rw");
    FileChannel fc = raf.getChannel();
    ByteBuffer buf = ByteBuffer.wrap(input);
    IOUtils.writeFully(fc, buf);
    raf.seek(0);
    raf.read(output);
    for (int i = 0; i < input.length; i++) {
      assertEquals(input[i], output[i]);
    }
    buf.rewind();
    IOUtils.writeFully(fc, buf, HALFWAY);
    for (int i = 0; i < HALFWAY; i++) {
      assertEquals(input[i], output[i]);
    }
    raf.seek(0);
    raf.read(output);
    for (int i = HALFWAY; i < input.length; i++) {
      assertEquals(input[i - HALFWAY], output[i]);
    }
  } finally {
    File f = new File(TEST_FILE_NAME);
    if (f.exists()) {
      f.delete();
    }
  }
}
 
Example 15
Project: dhus-core   File: FtpProductFile.java   Source Code and License Vote up 5 votes
@Override
public InputStream createInputStream (long offset) throws IOException
{
   File file = new File(product.getDownloadablePath());
   if (!doesExist())
   {
       throw new IOException("No read permission : " + file.getName());
   }

   // move to the appropriate offset and create input stream
   final RandomAccessFile raf = new RandomAccessFile(file, "r");
   try
   {
      raf.seek(offset);
      // The IBM jre needs to have both the stream and the random access file
      // objects closed to actually close the file
      return new RegulatedInputStream.Builder (new FileInputStream (
            raf.getFD())
      {
         public void close() throws IOException
         {
            super.close();
            raf.close();
         }
      }, TrafficDirection.OUTBOUND).userName(super.user.getUsername ()).
      copyStreamListener (
            new DownloadActionRecordListener (
         product.getUuid(), product.getIdentifier(), super.user)).
         streamSize(raf.length()).build ();
   }
   catch (IOException e)
   {
      raf.close();
      throw e;
   }
}
 
Example 16
Project: dev-courses   File: JDBCClobFile.java   Source Code and License Vote up 5 votes
public WriterAdapter(final File file,
                     final long pos)
                     throws FileNotFoundException, IOException {

    if (file == null) {
        throw new NullPointerException("file");
    }

    if (pos < 0) {
        throw new IllegalArgumentException("pos: " + pos);
    }

    ReaderAdapter reader = null;
    long          filePointer;

    try {
        reader      = new ReaderAdapter(file, pos, Long.MAX_VALUE);
        filePointer = reader.getFilePointer();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ex) {}
        }
    }

    m_randomAccessFile = new RandomAccessFile(file, "rw");

    m_randomAccessFile.seek(filePointer);
}
 
Example 17
Project: jdk8u-jdk   File: Basic.java   Source Code and License Vote up 4 votes
public static void main(String[] args) throws Exception {

        show(nonExistantFile);
        if (nonExistantFile.exists()) fail(nonExistantFile, "exists");

        show(rwFile);
        testFile(rwFile, true, 6);
        rwFile.delete();
        if (rwFile.exists())
            fail(rwFile, "could not delete");

        show(roFile);
        testFile(roFile, false, 0);

        show(thisDir);
        if (!thisDir.exists()) fail(thisDir, "does not exist");
        if (thisDir.isFile()) fail(thisDir, "is a file");
        if (!thisDir.isDirectory()) fail(thisDir, "is not a directory");
        if (!thisDir.canRead()) fail(thisDir, "is readable");
        if (!thisDir.canWrite()) fail(thisDir, "is writeable");
        String[] fs = thisDir.list();
        if (fs == null) fail(thisDir, "list() returned null");
        out.print("  [" + fs.length + "]");
        for (int i = 0; i < fs.length; i++)
            out.print(" " + fs[i]);
        out.println();
        if (fs.length == 0) fail(thisDir, "is empty");

        if (!nonExistantFile.createNewFile())
            fail(nonExistantFile, "could not create");
        nonExistantFile.deleteOnExit();

        if (!nonDir.mkdir())
            fail(nonDir, "could not create");

        if (!dir.renameTo(new File("x.Basic.dir2")))
            fail(dir, "failed to rename");

        if (System.getProperty("os.name").equals("SunOS")
            && System.getProperty("os.version").compareTo("5.6") >= 0) {
            if (bigFile.exists()) {
                bigFile.delete();
                if (bigFile.exists())
                    fail(bigFile, "could not delete");
            }
            RandomAccessFile raf = new RandomAccessFile(bigFile, "rw");
            long big = ((long)Integer.MAX_VALUE) * 2;
            try {
                raf.seek(big);
                raf.write('x');
                show(bigFile);
                testFile(bigFile, true, big + 1);
            } finally {
                raf.close();
            }
            bigFile.delete();
            if (bigFile.exists())
                fail(bigFile, "could not delete");
        } else {
            System.err.println("NOTE: Large files not supported on this system");
        }

    }
 
Example 18
Project: boohee_v5.6   File: SingleDownloadTask.java   Source Code and License Vote up 4 votes
protected RandomAccessFile getFile(File dir, String name, long offset) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(new File(dir, name), "rwd");
    raf.seek(0);
    return raf;
}
 
Example 19
Project: vlc-example-streamplayer   File: VLCUtil.java   Source Code and License Vote up 4 votes
private static boolean readArmAttributes(RandomAccessFile in, ElfData elf) throws IOException {
    byte[] bytes = new byte[elf.sh_size];
    in.seek(elf.sh_offset);
    in.readFully(bytes);

    // wrap bytes in a ByteBuffer to force endianess
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    buffer.order(elf.order);

    //http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044e/IHI0044E_aaelf.pdf
    //http://infocenter.arm.com/help/topic/com.arm.doc.ihi0045d/IHI0045D_ABI_addenda.pdf
    if (buffer.get() != 'A') // format-version
        return false;

    // sub-sections loop
    while (buffer.remaining() > 0) {
        int start_section = buffer.position();
        int length = buffer.getInt();
        String vendor = getString(buffer);
        if (vendor.equals("aeabi")) {
            // tags loop
            while (buffer.position() < start_section + length) {
                int start = buffer.position();
                int tag = buffer.get();
                int size = buffer.getInt();
                // skip if not Tag_File, we don't care about others
                if (tag != 1) {
                    buffer.position(start + size);
                    continue;
                }

                // attributes loop
                while (buffer.position() < start + size) {
                    tag = getUleb128(buffer);
                    if (tag == 6) { // CPU_arch
                        int arch = getUleb128(buffer);
                        elf.att_arch = CPU_archs[arch];
                    } else if (tag == 27) { // ABI_HardFP_use
                        getUleb128(buffer);
                        elf.att_fpu = true;
                    } else {
                        // string for 4=CPU_raw_name / 5=CPU_name / 32=compatibility
                        // string for >32 && odd tags
                        // uleb128 for other
                        tag %= 128;
                        if (tag == 4 || tag == 5 || tag == 32 || (tag > 32 && (tag & 1) != 0))
                            getString(buffer);
                        else
                            getUleb128(buffer);
                    }
                }
            }
            break;
        }
    }
    return true;
}
 
Example 20
Project: DAA_Converter   File: DAA_Reader.java   Source Code and License Vote up 3 votes
public DAA_Hit parseHit(RandomAccessFile raf, long filePointer, int accessPoint) {

		DAA_Hit hit = null;

		try {

			raf.seek(filePointer);

			ByteBuffer buffer = ByteBuffer.allocate(4);
			buffer.order(ByteOrder.LITTLE_ENDIAN);
			raf.read(buffer.array());
			int alloc = buffer.getInt();

			ByteBuffer hitBuffer = ByteBuffer.allocate(alloc);
			hitBuffer.order(ByteOrder.LITTLE_ENDIAN);
			raf.read(hitBuffer.array());

			// parsing query properties
			hit = new DAA_Hit();
			hit.parseQueryProperties(filePointer, hitBuffer, true, false);

			hitBuffer.position(accessPoint);

			// parsing match properties
			hit.parseHitProperties(header, hitBuffer, true);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return hit;

	}