Java Code Examples for java.io.RandomAccessFile

The following are top voted examples for showing how to use java.io.RandomAccessFile. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: PlayGround   File: NIO.java   Source Code and License 7 votes vote down vote up
public static void main(String[] args) throws IOException {
    RandomAccessFile aFile = new RandomAccessFile("/Users/zhenpeng/aa.txt", "rw");
    FileChannel inChannel = aFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(2);
    int bytesRead = inChannel.read(buf);
    while (bytesRead != -1) {
        buf.flip();
        while (buf.hasRemaining()) {
            System.out.print((char) buf.get());
        }
        buf.clear();
        //bytesRead = inChannel.read(buf);
        //buf.putChar('f');
        bytesRead = inChannel.read(buf);
    }
    aFile.close();
}
 
Example 2
Project: letv   File: QueueFile.java   Source Code and License 7 votes vote down vote up
private static void initialize(File file) throws IOException {
    File tempFile = new File(file.getPath() + ".tmp");
    RandomAccessFile raf = open(tempFile);
    try {
        raf.setLength(PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM);
        raf.seek(0);
        byte[] headerBuffer = new byte[16];
        writeInts(headerBuffer, 4096, 0, 0, 0);
        raf.write(headerBuffer);
        if (!tempFile.renameTo(file)) {
            throw new IOException("Rename failed!");
        }
    } finally {
        raf.close();
    }
}
 
Example 3
Project: react-native-videoplayer   File: ZipResourceFile.java   Source Code and License 6 votes vote down vote up
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 4
Project: CorePatch   File: BsPatch.java   Source Code and License 6 votes vote down vote up
/**
 * Transforms bytes from |oldData| into |newData| by applying byte-for-byte addends from
 * |patchData|. The number of bytes consumed from |oldData| and |patchData|, as well as the
 * number of bytes written to |newData|, is |diffLength|. The contents of the buffers are
 * ignored and overwritten, and no guarantee is made as to their contents when this method
 * returns. This is the core of the bsdiff patching algorithm. |buffer1.length| must equal
 * |buffer2.length|, and |buffer1| and |buffer2| must be distinct objects.
 *
 * @param diffLength the length of the BsDiff entry (how many bytes to read and apply).
 * @param patchData the input stream from the BsDiff patch containing diff bytes. This stream
 *                  must be positioned so that the first byte read is the first addend to be
 *                  applied to the first byte of data to be read from |oldData|.
 * @param oldData the old file, for the diff bytes to be applied to. This input source must be
 *                positioned so that the first byte read is the first byte of data to which the
 *                first byte of addends from |patchData| should be applied.
 * @param newData the stream to write the resulting data to.
 * @param buffer1 temporary buffer to use for data transformation; contents are ignored, may be
 *                overwritten, and are undefined when this method returns.
 * @param buffer2 temporary buffer to use for data transformation; contents are ignored, may be
 *                overwritten, and are undefined when this method returns.
 */
// Visible for testing only
static void transformBytes(
    final int diffLength,
    final InputStream patchData,
    final RandomAccessFile oldData,
    final OutputStream newData,
    final byte[] buffer1,
    final byte[] buffer2)
    throws IOException {
  int numBytesLeft = diffLength;
  while (numBytesLeft > 0) {
    final int numBytesThisRound = Math.min(numBytesLeft, buffer1.length);
    oldData.readFully(buffer1, 0, numBytesThisRound);
    readFully(patchData, buffer2, 0, numBytesThisRound);
    for (int i = 0; i < numBytesThisRound; i++) {
      buffer1[i] += buffer2[i];
    }
    newData.write(buffer1, 0, numBytesThisRound);
    numBytesLeft -= numBytesThisRound;
  }
}
 
Example 5
Project: jermit   File: XmodemSession.java   Source Code and License 6 votes vote down vote up
/**
 * Trim the CPM EOF byte (0x1A) from the end of a file.
 *
 * @param filename the name of the file to trim on the local filesystem
 */
protected void trimEOF(final String filename) {
    try {
        // SetLength() requires the file be open in read-write.
        RandomAccessFile contents = new RandomAccessFile(filename, "rw");
        while (contents.length() > 0) {
            contents.seek(contents.length() - 1);
            int ch = contents.read();
            if (ch == 0x1A) {
                contents.setLength(contents.length() - 1);
            } else {
                // Found a non-EOF byte
                break;
            }
        }
    } catch (IOException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
    }
}
 
Example 6
Project: cyberduck   File: FileBuffer.java   Source Code and License 6 votes vote down vote up
@Override
public void truncate(final Long length) {
    this.length = length;
    if(temporary.exists()) {
        try {
            final RandomAccessFile file = random();
            if(length < file.length()) {
                // Truncate current
                file.setLength(length);
            }
        }
        catch(IOException e) {
            log.warn(String.format("Failure truncating file %s to %d", temporary, length));
        }
    }
}
 
Example 7
Project: hadoop   File: MiniDFSCluster.java   Source Code and License 6 votes vote down vote up
public static boolean corruptBlock(File blockFile) throws IOException {
  if (blockFile == null || !blockFile.exists()) {
    return false;
  }
  // Corrupt replica by writing random bytes into replica
  Random random = new Random();
  RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
  FileChannel channel = raFile.getChannel();
  String badString = "BADBAD";
  int rand = random.nextInt((int)channel.size()/2);
  raFile.seek(rand);
  raFile.write(badString.getBytes());
  raFile.close();
  LOG.warn("Corrupting the block " + blockFile);
  return true;
}
 
Example 8
Project: alerta-fraude   File: LocalFilesystem.java   Source Code and License 6 votes vote down vote up
@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
       File file = new File(filesystemPathForURL(inputURL));

       if (!file.exists()) {
           throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
       }

       RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
       try {
           if (raf.length() >= size) {
               FileChannel channel = raf.getChannel();
               channel.truncate(size);
               return size;
           }

           return raf.length();
       } finally {
           raf.close();
       }


}
 
Example 9
Project: s-store   File: ScaledRAFile.java   Source Code and License 6 votes vote down vote up
ScaledRAFile(Database database, String name,
             boolean readonly) throws FileNotFoundException, IOException {

    this.appLog   = database.logger.appLog;
    this.readOnly = readonly;
    this.fileName = name;
    this.file     = new RandomAccessFile(name, readonly ? "r"
                                                        : "rw");

    int bufferScale = database.getProperties().getIntegerProperty(
        HsqlDatabaseProperties.hsqldb_raf_buffer_scale, 12);
    int bufferSize = 1 << bufferScale;

    buffer = new byte[bufferSize];
    ba     = new HsqlByteArrayInputStream(buffer);
}
 
Example 10
Project: hadoop-oss   File: NativeIO.java   Source Code and License 6 votes vote down vote up
/**
 * Create a FileInputStream that shares delete permission on the
 * file opened at a given offset, i.e. other process can delete
 * the file the FileInputStream is reading. Only Windows implementation
 * uses the native interface.
 */
public static FileInputStream getShareDeleteFileInputStream(File f, long seekOffset)
    throws IOException {
  if (!Shell.WINDOWS) {
    RandomAccessFile rf = new RandomAccessFile(f, "r");
    if (seekOffset > 0) {
      rf.seek(seekOffset);
    }
    return new FileInputStream(rf.getFD());
  } else {
    // Use Windows native interface to create a FileInputStream that
    // shares delete permission on the file opened, and set it to the
    // given offset.
    //
    FileDescriptor fd = NativeIO.Windows.createFile(
        f.getAbsolutePath(),
        NativeIO.Windows.GENERIC_READ,
        NativeIO.Windows.FILE_SHARE_READ |
            NativeIO.Windows.FILE_SHARE_WRITE |
            NativeIO.Windows.FILE_SHARE_DELETE,
        NativeIO.Windows.OPEN_EXISTING);
    if (seekOffset > 0)
      NativeIO.Windows.setFilePointer(fd, seekOffset, NativeIO.Windows.FILE_BEGIN);
    return new FileInputStream(fd);
  }
}
 
Example 11
Project: oneKey2Alarm   File: messages.java   Source Code and License 6 votes vote down vote up
public void writeTxtToFile(String strcontent, String filePath, String fileName) {
    // �����ļ���֮���������ļ�����Ȼ�����
    makeFilePath(filePath, fileName);
 
    String strFilePath = filePath + fileName;
    // ÿ��д��ʱ��������д
    String strContent = strcontent + "\r\n";
    try {
        File file = new File(strFilePath);
        if (!file.exists()) {
            Log.d("TestFile", "Create the file:" + strFilePath);
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        RandomAccessFile raf = new RandomAccessFile(file, "rwd");
        raf.seek(file.length());
        raf.write(strContent.getBytes());
        raf.close();
 
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 12
Project: flume-release-1.7.0   File: TestLogFile.java   Source Code and License 6 votes vote down vote up
@Test(expected = CorruptEventException.class)
public void testPutGetCorruptEvent() throws Exception {
  final LogFile.RandomReader logFileReader =
      LogFileFactory.getRandomReader(dataFile, null, true);
  final FlumeEvent eventIn = TestUtils.newPersistableEvent(2500);
  final Put put = new Put(++transactionID, WriteOrderOracle.next(), eventIn);
  ByteBuffer bytes = TransactionEventRecord.toByteBuffer(put);
  FlumeEventPointer ptr = logFileWriter.put(bytes);
  logFileWriter.commit(TransactionEventRecord.toByteBuffer(
      new Commit(transactionID, WriteOrderOracle.next())));
  logFileWriter.sync();
  final int offset = ptr.getOffset();
  RandomAccessFile writer = new RandomAccessFile(dataFile, "rw");
  writer.seek(offset + 1500);
  writer.write((byte) 45);
  writer.write((byte) 12);
  writer.getFD().sync();
  logFileReader.get(offset);

  // Should have thrown an exception by now.
  Assert.fail();
}
 
Example 13
Project: org.alloytools.alloy   File: OurPNGWriter.java   Source Code and License 6 votes vote down vote up
/**
 * Write the given chunk into the given file; Note: data.length must be at
 * least 4.
 */
private static void writeChunk(RandomAccessFile file, int[] data) throws IOException {
	int crc = (-1), len = data.length - 4;
	file.write((len >>> 24) & 255);
	file.write((len >>> 16) & 255);
	file.write((len >>> 8) & 255);
	file.write(len & 255);
	for (int i = 0; i < data.length; i++) {
		int x = data[i];
		crc = table[(crc ^ x) & 255] ^ (crc >>> 8);
		file.write(x & 255);
	}
	crc = crc ^ (-1);
	file.write((crc >>> 24) & 255);
	file.write((crc >>> 16) & 255);
	file.write((crc >>> 8) & 255);
	file.write(crc & 255);
}
 
Example 14
Project: alfresco-repository   File: FSDirectory.java   Source Code and License 6 votes vote down vote up
public void close() throws IOException {
  lock.readLock().lock();
  if (isOpen) {
    lock.readLock().unlock();
    lock.writeLock().lock();
    try {
      if (isOpen) {
        for (RandomAccessFile file : fileMap.values())
        {
            file.close();
        }
        fileMap.clear();
        isOpen=false;
      }
    }
    finally
    {
        lock.writeLock().unlock();
    }
  }
  else {
    lock.readLock().unlock();
  }
}
 
Example 15
Project: VirtualHook   File: FileUtils.java   Source Code and License 6 votes vote down vote up
public boolean LockExclusive(File targetFile) {

            if (targetFile == null) {
                return false;
            }
            try {
                File lockFile = new File(targetFile.getParentFile().getAbsolutePath().concat("/lock"));
                if (!lockFile.exists()) {
                    lockFile.createNewFile();
                }
                RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile.getAbsolutePath(), "rw");
                FileChannel channel = randomAccessFile.getChannel();
                java.nio.channels.FileLock lock = channel.lock();
                if (!lock.isValid()) {
                    return false;
                }
                RefCntInc(lockFile.getAbsolutePath(), lock, randomAccessFile, channel);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
 
Example 16
Project: spring2017java   File: FileIODemoSection3.java   Source Code and License 6 votes vote down vote up
public void readUsingRandomAccessFile() {
    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile("input.txt", "r");
        int x = Integer.parseInt(randomAccessFile.readLine());
        double y = Double.parseDouble(randomAccessFile.readLine());
        String s = randomAccessFile.readLine();
        System.out.println(x);
        System.out.println(y);
        System.out.println(s);
    } catch (FileNotFoundException fnfe) {
        System.out.println("Could not find the input file");
    } catch (IOException ioe) {
        System.out.println("Can't read anymore!");
    }

}
 
Example 17
Project: dataset-lib   File: StreamThread.java   Source Code and License 6 votes vote down vote up
public ByteBuffer call() throws Exception {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    buff = ByteBuffer.allocate(bufferSize);
    serverSocketChannel.socket().bind(new InetSocketAddress(port));
    RandomAccessFile temp = new RandomAccessFile(tempName, "rw");
    MappedByteBuffer b;
    while (!stop.isLocked()) {
        sync=0;
        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.read(buff);
        FileChannel channel = temp.getChannel();
        channel.write(buff);
        if (!pause.isLocked()) {
            b = channel.map(MapMode.READ_WRITE, 0, (long) bufferSize);
            sync = 1;
            if(sync==2){
            b.clear();
            }
        }
        buff.clear();
    }
    temp.close();
    return null;
}
 
Example 18
Project: parabuild-ci   File: ScaledRAFile.java   Source Code and License 6 votes vote down vote up
ScaledRAFile(Database database, String name,
             boolean readonly) throws FileNotFoundException, IOException {

    this.appLog   = database.logger.appLog;
    this.readOnly = readonly;
    this.fileName = name;
    this.file     = new RandomAccessFile(name, readonly ? "r"
                                                        : "rw");

    int bufferScale = database.getProperties().getIntegerProperty(
        HsqlDatabaseProperties.hsqldb_raf_buffer_scale, 12);
    int bufferSize = 1 << bufferScale;

    buffer     = new byte[bufferSize];
    ba         = new HsqlByteArrayInputStream(buffer);
    fileLength = length();
}
 
Example 19
Project: KrGallery   File: ImageLoader.java   Source Code and License 6 votes vote down vote up
public static void fillPhotoSizeWithBytes(PhotoSize photoSize) {
    if (photoSize == null || photoSize.bytes != null) {
        return;
    }
    File file = FileLoader.getPathToAttach(photoSize, true);
    try {
        RandomAccessFile f = new RandomAccessFile(file, "r");
        int len = (int) f.length();
        if (len < 20000) {
            photoSize.bytes = new byte[(int) f.length()];
            f.readFully(photoSize.bytes, 0, photoSize.bytes.length);
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
}
 
Example 20
Project: hadoop   File: FadvisedFileRegion.java   Source Code and License 6 votes vote down vote up
public FadvisedFileRegion(RandomAccessFile file, long position, long count,
    boolean manageOsCache, int readaheadLength, ReadaheadPool readaheadPool,
    String identifier, int shuffleBufferSize, 
    boolean shuffleTransferToAllowed) throws IOException {
  super(file.getChannel(), position, count);
  this.manageOsCache = manageOsCache;
  this.readaheadLength = readaheadLength;
  this.readaheadPool = readaheadPool;
  this.fd = file.getFD();
  this.identifier = identifier;
  this.fileChannel = file.getChannel();
  this.count = count;
  this.position = position;
  this.shuffleBufferSize = shuffleBufferSize;
  this.shuffleTransferToAllowed = shuffleTransferToAllowed;
}
 
Example 21
Project: FApkSigner   File: ApkVerifier.java   Source Code and License 6 votes vote down vote up
/**
 * Verifies the APK's signatures and returns the result of verification. The APK can be
 * considered verified iff the result's {@link Result#isVerified()} returns {@code true}.
 * The verification result also includes errors, warnings, and information about signers.
 *
 * @throws IOException if an I/O error is encountered while reading the APK
 * @throws ApkFormatException if the APK is malformed
 * @throws NoSuchAlgorithmException if the APK's signatures cannot be verified because a
 *         required cryptographic algorithm implementation is missing
 * @throws IllegalStateException if this verifier's configuration is missing required
 *         information.
 */
public Result verify() throws IOException, ApkFormatException, NoSuchAlgorithmException,
        IllegalStateException {
    Closeable in = null;
    try {
        DataSource apk;
        if (mApkDataSource != null) {
            apk = mApkDataSource;
        } else if (mApkFile != null) {
            RandomAccessFile f = new RandomAccessFile(mApkFile, "r");
            in = f;
            apk = DataSources.asDataSource(f, 0, f.length());
        } else {
            throw new IllegalStateException("APK not provided");
        }
        return verify(apk);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}
 
Example 22
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: StoreCheckpoint.java   Source Code and License 6 votes vote down vote up
public StoreCheckpoint(final String scpPath) throws IOException {
    File file = new File(scpPath);
    MappedFile.ensureDirOK(file.getParent());
    boolean fileExists = file.exists();

    this.randomAccessFile = new RandomAccessFile(file, "rw");
    this.fileChannel = this.randomAccessFile.getChannel();
    this.mappedByteBuffer = fileChannel.map(MapMode.READ_WRITE, 0, MappedFile.OS_PAGE_SIZE);

    if (fileExists) {
        log.info("store checkpoint file exists, " + scpPath);
        this.physicMsgTimestamp = this.mappedByteBuffer.getLong(0);
        this.logicsMsgTimestamp = this.mappedByteBuffer.getLong(8);
        this.indexMsgTimestamp = this.mappedByteBuffer.getLong(16);

        log.info("store checkpoint file physicMsgTimestamp " + this.physicMsgTimestamp + ", "
            + UtilAll.timeMillisToHumanString(this.physicMsgTimestamp));
        log.info("store checkpoint file logicsMsgTimestamp " + this.logicsMsgTimestamp + ", "
            + UtilAll.timeMillisToHumanString(this.logicsMsgTimestamp));
        log.info("store checkpoint file indexMsgTimestamp " + this.indexMsgTimestamp + ", "
            + UtilAll.timeMillisToHumanString(this.indexMsgTimestamp));
    } else {
        log.info("store checkpoint file not exists, " + scpPath);
    }
}
 
Example 23
Project: MaxSim   File: ELFHeader.java   Source Code and License 6 votes vote down vote up
public void writeELFHeader64ToFile(ELFDataOutputStream os, RandomAccessFile fis) throws IOException {

        // 64 byte header is written.
        // Write the e_ident[16] byte array into the object file.
        fis.write(e_ident);
        os.write_Elf64_Half(e_type);
        os.write_Elf64_Half(e_machine);
        os.write_Elf64_Word(e_version);
        os.write_Elf64_Addr(e_entry);
        os.write_Elf64_Off(e_phoff);
        os.write_Elf64_Off(e_shoff);
        os.write_Elf64_Word(e_flags);
        os.write_Elf64_Half(e_ehsize);
        os.write_Elf64_Half(e_phentsize);
        os.write_Elf64_Half(e_phnum);
        os.write_Elf64_Half(e_shentsize);
        os.write_Elf64_Half(e_shnum);
        os.write_Elf64_Half(e_shstrndx);

    }
 
Example 24
Project: incubator-netbeans   File: ModuleOperationsTest.java   Source Code and License 6 votes vote down vote up
public void testOperationActions() throws Exception { // #72397
    final NbModuleProject project = generateStandaloneModule("module");
    cgpi.setProject(project);
    DialogDisplayerImpl dd = (DialogDisplayerImpl) Lookup.getDefault().lookup(DialogDisplayer.class);
    FileObject lock = FileUtil.createData(project.getProjectDirectory(), "build/testuserdir/lock");
    RandomAccessFile raf = new RandomAccessFile(FileUtil.toFile(lock), "rw");
    FileLock lck = raf.getChannel().lock();
    EventQueue.invokeAndWait(new Runnable() {
        @Override public void run() {
            ((ContextAwareAction) CommonProjectActions.deleteProjectAction()).createContextAwareInstance(Lookups.singleton(project)).actionPerformed(null);
        }
    });
    assertNotNull("warning message emitted", dd.getLastNotifyDescriptor());
    assertEquals("warning message emitted", dd.getLastNotifyDescriptor().getMessage(),
            Bundle.ERR_ModuleIsBeingRun());
    dd.reset();
    lck.release();
    raf.close();
    lock.delete();
    EventQueue.invokeAndWait(new Runnable() {
        @Override public void run() {
            CommonProjectActions.deleteProjectAction().actionPerformed(null);
        }
    });
    assertNull("no warning message", dd.getLastNotifyDescriptor());
}
 
Example 25
Project: incubator-netbeans   File: StreamUtils.java   Source Code and License 6 votes vote down vote up
public static void transferData(
        final RandomAccessFile in, 
        final OutputStream out, 
        final long max,
        final Progress progress) throws IOException {
    final byte[] buffer = new byte[FileUtils.BUFFER_SIZE];
    
    long total = 0;
    int length = 0;
    
    progress.setPercentage(Progress.START);
    while (((length = in.read(buffer)) != -1) && (total < max)) {
        total += length;
        out.write(
                buffer, 
                0, 
                (int) (total < max ? length : length - (total - max)));
        
        if (total < max) {
            progress.setPercentage(Progress.COMPLETE * total / max);
        }
    }
    progress.setPercentage(Progress.COMPLETE);
    
    out.flush();
}
 
Example 26
Project: HeadlineNews   File: CacheUtils.java   Source Code and License 6 votes vote down vote up
private static byte[] readFile2Bytes(final File file) {
    FileChannel fc = null;
    try {
        fc = new RandomAccessFile(file, "r").getChannel();
        int size = (int) fc.size();
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, size).load();
        byte[] data = new byte[size];
        mbb.get(data, 0, size);
        return data;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
 
Example 27
Project: openaudible   File: RealFileReader.java   Source Code and License 6 votes vote down vote up
@Override
protected Tag getTag(RandomAccessFile raf) throws CannotReadException, IOException {
    final RealChunk cont = findContChunk(raf);
    final DataInputStream dis = cont.getDataInputStream();
    final String title = Utils.readString(dis, Utils.readUint16(dis));
    final String author = Utils.readString(dis, Utils.readUint16(dis));
    final String copyright = Utils.readString(dis, Utils.readUint16(dis));
    final String comment = Utils.readString(dis, Utils.readUint16(dis));
    final RealTag rv = new RealTag();
    // NOTE: frequently these fields are off-by-one, thus the crazy
    // logic below...
    try {
        rv.addField(FieldKey.TITLE, (title.length() == 0 ? author : title));
        rv.addField(FieldKey.ARTIST, title.length() == 0 ? copyright : author);
        rv.addField(FieldKey.COMMENT, comment);
    } catch (FieldDataInvalidException fdie) {
        throw new RuntimeException(fdie);
    }
    return rv;
}
 
Example 28
Project: buildAPKsSamples   File: BackupRestoreActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Another helper; this one reads the current UI state and writes that
 * to the persistent store, then tells the backup manager that we need
 * a backup.
 */
void recordNewUIState() {
    boolean addMayo = mAddMayoCheckbox.isChecked();
    boolean addTomato = mAddTomatoCheckbox.isChecked();
    int whichFilling = mFillingGroup.getCheckedRadioButtonId();
    try {
        synchronized (BackupRestoreActivity.sDataLock) {
            RandomAccessFile file = new RandomAccessFile(mDataFile, "rw");
            writeDataToFileLocked(file, addMayo, addTomato, whichFilling);
        }
    } catch (IOException e) {
        Log.e(TAG, "Unable to record new UI state");
    }

    mBackupManager.dataChanged();
}
 
Example 29
Project: MaxSim   File: ELFProgramHeaderTable.java   Source Code and License 5 votes vote down vote up
/**
 * The <code>read()</code> method reqds the program header table from the specified
 * input stream. This method assumes that the input stream has been positioned at
 * the beginning of the program header table.
 * @param fis the input stream from which to read the program header table
 * @throws IOException if there is a problem reading the header table from the input
 */
public void read(RandomAccessFile fis) throws IOException {
    if (entries.length == 0) {
        return;
    }
    // seek to the beginning of the table
    fis.seek(header.e_phoff);
    final ELFDataInputStream is = new ELFDataInputStream(header, fis);
    // read each entry
    for (int cntr = 0; cntr < entries.length; cntr++) {
        entries[cntr] = readEntry(fis, is);
    }
}
 
Example 30
Project: apfloat   File: DiskDataStorage.java   Source Code and License 5 votes vote down vote up
private void init()
    throws ApfloatRuntimeException
{
    ApfloatContext ctx = ApfloatContext.getContext();
    FilenameGenerator generator = ctx.getFilenameGenerator();

    this.filename = generator.generateFilename();

    this.file = new File(this.filename);

    try
    {
        if (!this.file.createNewFile())
        {
            throw new BackingStorageException("Failed to create new file \"" + this.filename + '\"');
        }

        // Ensure file is deleted always
        this.file.deleteOnExit();

        this.randomAccessFile = new RandomAccessFile(this.file, "rw");
    }
    catch (IOException ioe)
    {
        throw new BackingStorageException("Unable to access file \"" + this.filename + '\"', ioe);
    }

    this.fileChannel = this.randomAccessFile.getChannel();

    referenceFileStorage(this);     // To put to reference queue after garbage collection
}
 
Example 31
Project: letv   File: ApkExternalInfoTool.java   Source Code and License 5 votes vote down vote up
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 32
Project: MetadataEditor   File: AbstractLyrics3.java   Source Code and License 5 votes vote down vote up
/**
 * @param file
 * @throws IOException
 */
public void delete(RandomAccessFile file) throws IOException
{
    long filePointer;
    ID3v1Tag id3v1tag = new ID3v1Tag();


}
 
Example 33
Project: app-logbrowser   File: LogFileHandler.java   Source Code and License 5 votes vote down vote up
private int readByte( final RandomAccessFile file, final long position )
{
    try
    {
        file.seek( position );
        return file.readByte();
    }
    catch ( IOException e )
    {
        return -1;
    }
}
 
Example 34
Project: hadoop   File: TestClientReportBadBlock.java   Source Code and License 5 votes vote down vote up
/**
 * Corrupt a block on a data node. Replace the block file content with content
 * of 1, 2, ...BLOCK_SIZE.
 * 
 * @param block
 *          the ExtendedBlock to be corrupted
 * @param dn
 *          the data node where the block needs to be corrupted
 * @throws FileNotFoundException
 * @throws IOException
 */
private static void corruptBlock(final ExtendedBlock block, final DataNode dn)
    throws FileNotFoundException, IOException {
  final File f = DataNodeTestUtils.getBlockFile(
      dn, block.getBlockPoolId(), block.getLocalBlock());
  final RandomAccessFile raFile = new RandomAccessFile(f, "rw");
  final byte[] bytes = new byte[(int) BLOCK_SIZE];
  for (int i = 0; i < BLOCK_SIZE; i++) {
    bytes[i] = (byte) (i);
  }
  raFile.write(bytes);
  raFile.close();
}
 
Example 35
Project: mobile-store   File: NanoHTTPD.java   Source Code and License 5 votes vote down vote up
private RandomAccessFile getTmpBucket() {
    try {
        TempFile tempFile = tempFileManager.createTempFile();
        return new RandomAccessFile(tempFile.getName(), "rw");
    } catch (Exception e) {
    	throw new Error(e); // we won't recover, so throw an error
    }
}
 
Example 36
Project: morpheus-core   File: MappedArrayOfLongs.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
/** Custom serialization */
private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException {
    this.file = MappedArrayConstructor.randomFile(true);
    this.length = is.readInt();
    this.defaultValue = is.readLong();
    this.channel = new RandomAccessFile(file, "rw").getChannel();
    this.buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, BYTE_COUNT * length).asLongBuffer();
    for (int i=0; i<length; ++i) {
        final long value = is.readLong();
        this.setLong(i, value);
    }
}
 
Example 37
Project: AnimationsDemo   File: MCPTool.java   Source Code and License 5 votes vote down vote up
/**
 * 读取数据
 * @param path 文件路径
 * @param password 解密密钥
 * @return 被该工具写入的数据(如:渠道号)
 * @throws Exception
 */
private static byte[] read(File path, String password) throws Exception {
	byte[] bytesContent = null;
	byte[] bytesMagic = SIG.getBytes(CHARSET_NAME);
	byte[] bytes = new byte[bytesMagic.length];
	RandomAccessFile raf = new RandomAccessFile(path, "r");
	Object[] versions = getVersion(raf);
	long index = (long) versions[0];
	String version = (String) versions[1];
	if (VERSION_1_1.equals(version)) {
		bytes = new byte[1];
		index -= bytes.length;
		readFully(raf, index, bytes); // 读取内容长度;
		boolean isEncrypt = bytes[0] == 1;

		bytes = new byte[2];
		index -= bytes.length;
		readFully(raf, index, bytes); // 读取内容长度;
		int lengthContent = stream2Short(bytes, 0);

		bytesContent = new byte[lengthContent];
		index -= lengthContent;
		readFully(raf, index, bytesContent); // 读取内容;

		if (isEncrypt && password != null && password.length() > 0) {
			bytesContent = decrypt(password, bytesContent);
		}
	}
	raf.close();
	return bytesContent;
}
 
Example 38
Project: AndroidVideoCache   File: Files.java   Source Code and License 5 votes vote down vote up
static void modify(File file) throws IOException {
    long size = file.length();
    if (size == 0) {
        recreateZeroSizeFile(file);
        return;
    }

    RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
    accessFile.seek(size - 1);
    byte lastByte = accessFile.readByte();
    accessFile.seek(size - 1);
    accessFile.write(lastByte);
    accessFile.close();
}
 
Example 39
Project: androidthings-kuman-sm9   File: SystemHelper.java   Source Code and License 5 votes vote down vote up
public Integer getCpuTemperature() {
    Integer temp = null;
    try (RandomAccessFile reader = new RandomAccessFile("/sys/class/thermal/thermal_zone0/temp", "r")) {
        temp = Math.round(Integer.parseInt(reader.readLine()) / 1000f);
    } catch (IOException e) {
        Timber.e(e);
    }
    return temp;
}
 
Example 40
Project: GitHub   File: TinkerZipFile.java   Source Code and License 5 votes vote down vote up
/**
 * Closes this zip file. This method is idempotent. This method may cause I/O if the
 * zip file needs to be deleted.
 *
 * @throws IOException
 *             if an IOException occurs.
 */
public void close() throws IOException {
    // guard.close();
    RandomAccessFile localRaf = raf;
    if (localRaf != null) { // Only close initialized instances
        synchronized (localRaf) {
            raf = null;
            localRaf.close();
        }
        if (fileToDeleteOnClose != null) {
            fileToDeleteOnClose.delete();
            fileToDeleteOnClose = null;
        }
    }
}