Example usage for java.io RandomAccessFile seek

List of usage examples for java.io RandomAccessFile seek

Introduction

In this page you can find the example usage for java.io RandomAccessFile seek.

Prototype

public void seek(long pos) throws IOException 

Source Link

Document

Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

Usage

From source file:org.multibit.file.FileHandler.java

/**
 * Delete a file with an overwrite of all of the data.
 * /*  w  w  w  .j  a va 2 s. c  o  m*/
 * Set bit patterns are used rather than random numbers to avoid a
 * futex_wait_queue_me error on Linux systems (related to /dev/random usage)
 * 
 * @param file
 * @throws IOException
 */
public static void secureDelete(File file) throws IOException {
    log.debug("Start of secureDelete");

    RandomAccessFile raf = null;
    if (file != null && file.exists()) {
        try {
            // Prep for file delete as this can be fiddly on windows.
            // Make sure it is writable and any references to it are garbage
            // collected and finalized.
            file.setWritable(true);
            System.gc();

            long length = file.length();
            raf = new RandomAccessFile(file, "rws");
            raf.seek(0);
            raf.getFilePointer();
            int pos = 0;
            while (pos < length) {
                raf.write(SECURE_DELETE_FILL_BYTES);
                pos += SECURE_DELETE_FILL_BYTES.length;
            }
        } finally {
            if (raf != null) {
                raf.close();
                raf = null;
            }
        }
        boolean deleteSuccess = file.delete();
        log.debug("Result of delete of file '" + file.getAbsolutePath() + "' was " + deleteSuccess);
    }
    log.debug("End of secureDelete");
}

From source file:com.tencent.wcdb.sample.repairdb.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Extract test database from assets.
    new AsyncTask<Void, Void, Void>() {
        @Override//from  w  ww . ja v  a 2  s  .co  m
        protected Void doInBackground(Void... params) {
            File dbFile = getDatabasePath(DBHelper.DATABASE_NAME);

            if (!dbFile.exists()) {
                dbFile.getParentFile().mkdirs();

                InputStream in = null;
                OutputStream out = null;
                try {
                    byte[] buffer = new byte[1024];
                    in = getAssets().open(DBHelper.DATABASE_NAME);
                    out = new FileOutputStream(dbFile);
                    int len;
                    while ((len = in.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    if (in != null)
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                    if (out != null)
                        try {
                            out.close();
                        } catch (IOException e) {
                        }
                }
            }
            return null;
        }
    }.execute();

    setContentView(R.layout.activity_main);

    mListView = (ListView) findViewById(R.id.list);
    mAdapter = new SimpleCursorAdapter(this, R.layout.main_listitem, null, new String[] { "a", "b" },
            new int[] { R.id.list_tv_a, R.id.list_tv_b }, 0);

    mListView.setAdapter(mAdapter);

    findViewById(R.id.btn_init_db).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AsyncTask<Void, Void, SQLiteException>() {
                @Override
                protected void onPreExecute() {
                    mAdapter.changeCursor(null);
                }

                @Override
                protected SQLiteException doInBackground(Void... params) {
                    if (mDB != null && mDB.isOpen()) {
                        mDBHelper.close();
                        mDB = null;
                    }

                    try {
                        mDBHelper.setWriteAheadLoggingEnabled(true);
                        mDB = mDBHelper.getWritableDatabase();

                        // After successfully opened the database, backup its master info.
                        RepairKit.MasterInfo.save(mDB, mDB.getPath() + "-mbak", DBHelper.PASSPHRASE);
                    } catch (SQLiteException e) {
                        // Failed to open database, probably due to corruption.
                        mDB = null;
                        return e;
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(SQLiteException e) {
                    if (e == null) {
                        // Database is successfully opened, query and refresh ListView.
                        Cursor cursor = mDB.rawQuery("SELECT rowid as _id, a, b FROM t1;", null);
                        mAdapter.changeCursor(cursor);

                        Toast.makeText(MainActivity.this, "Database is successfully opened.",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        // Database could not be opened, show toast.
                        Toast.makeText(MainActivity.this,
                                "Database cannot be opened, exception: " + e.getMessage(), Toast.LENGTH_LONG)
                                .show();
                    }
                }
            }.execute();
        }
    });

    findViewById(R.id.btn_corrupt_db).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AsyncTask<Void, Void, Exception>() {
                @Override
                protected void onPreExecute() {
                    mAdapter.changeCursor(null);
                }

                @Override
                protected Exception doInBackground(Void... params) {
                    if (mDB != null && mDB.isOpen()) {
                        mDBHelper.close();
                        mDB = null;
                    }

                    // Write random noise to the first page to corrupt the database.
                    RandomAccessFile raf = null;
                    try {
                        File dbFile = getDatabasePath(DBHelper.DATABASE_NAME);
                        raf = new RandomAccessFile(dbFile, "rw");
                        byte[] buffer = new byte[1024];
                        new Random().nextBytes(buffer);
                        raf.seek(0);
                        raf.write(buffer);
                    } catch (IOException e) {
                        return e;
                    } finally {
                        if (raf != null)
                            try {
                                raf.close();
                            } catch (IOException e) {
                            }
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(Exception e) {
                    if (e == null) {
                        Toast.makeText(MainActivity.this, "Database is now CORRUPTED!", Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        Toast.makeText(MainActivity.this, "Unable to overwrite database: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                }
            }.execute();
        }
    });

    findViewById(R.id.btn_repair_db).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new AsyncTask<Void, Void, SQLiteException>() {
                @Override
                protected void onPreExecute() {
                    mAdapter.changeCursor(null);
                }

                @Override
                protected SQLiteException doInBackground(Void... params) {
                    if (mDB != null && mDB.isOpen()) {
                        mDBHelper.close();
                        mDB = null;
                    }

                    RepairKit.MasterInfo master = null;
                    File dbFile = getDatabasePath(DBHelper.DATABASE_NAME);
                    File masterFile = new File(dbFile.getPath() + "-mbak");
                    File newDbFile = getDatabasePath(DBHelper.DATABASE_NAME + "-recover");

                    if (masterFile.exists()) {
                        try {
                            master = RepairKit.MasterInfo.load(masterFile.getPath(), DBHelper.PASSPHRASE, null);
                        } catch (SQLiteException e) {
                            // Could not load master info. Maybe backup file itself corrupted?
                        }
                    }

                    RepairKit repair = null;
                    try {
                        repair = new RepairKit(dbFile.getPath(), // corrupted database file
                                DBHelper.PASSPHRASE, // passphrase to the database
                                DBHelper.CIPHER_SPEC, // cipher spec to the database
                                master // backup master info just loaded
                        );

                        if (newDbFile.exists())
                            newDbFile.delete();

                        SQLiteDatabase newDb = SQLiteDatabase.openOrCreateDatabase(newDbFile,
                                DBHelper.PASSPHRASE, DBHelper.CIPHER_SPEC, null, DBHelper.ERROR_HANDLER);
                        boolean result = repair.output(newDb, 0);
                        if (!result) {
                            throw new SQLiteException("Repair returns false on output.");
                        }

                        newDb.setVersion(DBHelper.DATABASE_VERSION);
                        newDb.close();
                        repair.release();
                        repair = null;

                        if (!dbFile.delete() || !newDbFile.renameTo(dbFile))
                            throw new SQLiteException("Cannot rename database.");
                    } catch (SQLiteException e) {
                        return e;
                    } finally {
                        if (repair != null)
                            repair.release();
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(SQLiteException e) {
                    if (e == null) {
                        Toast.makeText(MainActivity.this, "Repair succeeded.", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Repair failed: " + e.getMessage(), Toast.LENGTH_LONG)
                                .show();
                    }
                }
            }.execute();
        }
    });
}

From source file:com.asakusafw.runtime.util.lock.LocalFileLockProvider.java

@Override
public LocalFileLockObject<T> tryLock(T target) throws IOException {
    if (baseDirectory.mkdirs() == false && baseDirectory.isDirectory() == false) {
        throw new IOException(MessageFormat.format("Failed to create lock directory: {0}", baseDirectory));
    }/*from ww w  .ja  v a  2s  .  co  m*/
    String fileName = String.format("%08x.lck", target == null ? -1 : target.hashCode()); //$NON-NLS-1$
    File lockFile = new File(baseDirectory, fileName);
    RandomAccessFile fd = new RandomAccessFile(lockFile, "rw"); //$NON-NLS-1$
    boolean success = false;
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug(MessageFormat.format("Start to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$
                    target, lockFile));
        }
        FileLock lockEntity = getLock(target, lockFile, fd);
        if (lockEntity == null) {
            return null;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Finished to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$
                        target, lockFile));
            }
            try {
                fd.seek(0L);
                fd.setLength(0L);
                fd.write(String.valueOf(target).getBytes(ENCODING));
                success = true;
                return new LocalFileLockObject<>(target, lockFile, fd, lockEntity);
            } finally {
                if (success == false) {
                    lockEntity.release();
                }
            }
        }
    } finally {
        if (success == false) {
            fd.close();
        }
    }
}

From source file:com.aol.advertising.qiao.injector.file.AbstractFileTailer.java

protected long checksum(RandomAccessFile raFile) throws IOException, InsufficientFileLengthException {
    long pos = raFile.getFilePointer();
    try {//  w  ww  .ja v a 2  s .  com
        byte[] buffer = new byte[checksumByteLength];
        raFile.seek(0);
        int n = raFile.read(buffer);
        if (n < checksumByteLength) {
            String s;
            logger.warn(s = ("not enough data for checksum: current file size=" + n));
            throw new InsufficientFileLengthException(s);
        }

        synchronized (_crc) {
            _crc.reset();
            _crc.update(buffer);

            return _crc.getValue();
        }
    } finally {
        raFile.seek(pos);
    }

}

From source file:org.apache.flume.channel.file.TestFileChannelRestart.java

@Test
public void testCorruptCheckpointVersionMostSignificant4Bytes() throws Exception {
    Map<String, String> overrides = Maps.newHashMap();
    channel = createFileChannel(overrides);
    channel.start();//from w  w w  .ja v a 2  s.co  m
    Assert.assertTrue(channel.isOpen());
    Set<String> in = putEvents(channel, "restart", 10, 100);
    Assert.assertEquals(100, in.size());
    forceCheckpoint(channel);
    channel.stop();
    File checkpoint = new File(checkpointDir, "checkpoint");
    RandomAccessFile writer = new RandomAccessFile(checkpoint, "rw");
    writer.seek(EventQueueBackingStoreFile.INDEX_VERSION * Serialization.SIZE_OF_LONG);
    writer.write(new byte[] { (byte) 1, (byte) 5 });
    writer.getFD().sync();
    writer.close();
    channel = createFileChannel(overrides);
    channel.start();
    Assert.assertTrue(channel.isOpen());
    Set<String> out = consumeChannel(channel);
    Assert.assertTrue(channel.didFullReplayDueToBadCheckpointException());
    compareInputAndOut(in, out);
}

From source file:org.apache.flume.channel.file.TestFileChannelRestart.java

@Test
public void testCorruptCheckpointCompleteMarkerMostSignificant4Bytes() throws Exception {
    Map<String, String> overrides = Maps.newHashMap();
    channel = createFileChannel(overrides);
    channel.start();/*  w  ww  . ja  va2s . c om*/
    Assert.assertTrue(channel.isOpen());
    Set<String> in = putEvents(channel, "restart", 10, 100);
    Assert.assertEquals(100, in.size());
    forceCheckpoint(channel);
    channel.stop();
    File checkpoint = new File(checkpointDir, "checkpoint");
    RandomAccessFile writer = new RandomAccessFile(checkpoint, "rw");
    writer.seek(EventQueueBackingStoreFile.INDEX_CHECKPOINT_MARKER * Serialization.SIZE_OF_LONG);
    writer.write(new byte[] { (byte) 1, (byte) 5 });
    writer.getFD().sync();
    writer.close();
    channel = createFileChannel(overrides);
    channel.start();
    Assert.assertTrue(channel.isOpen());
    Set<String> out = consumeChannel(channel);
    Assert.assertTrue(channel.didFullReplayDueToBadCheckpointException());
    compareInputAndOut(in, out);
}

From source file:com.android.strictmodetest.StrictModeActivity.java

private void fileReadLoop() {
    RandomAccessFile raf = null;
    File filename = getFileStreamPath("test.dat");
    try {//from www  .j a va2 s . c  o m
        long sumNanos = 0;
        byte[] buf = new byte[512];

        //raf = new RandomAccessFile(filename, "rw");
        //raf.write(buf);
        //raf.close();
        //raf = null;

        // The data's almost certainly cached -- it's not clear what we're testing here
        raf = new RandomAccessFile(filename, "r");
        raf.seek(0);
        raf.read(buf);
    } catch (IOException e) {
        Log.e(TAG, "File read failed", e);
    } finally {
        try {
            if (raf != null)
                raf.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.apache.flume.channel.file.TestFileChannelRestart.java

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();/*from  w ww.j  av a  2  s. c  o  m*/
    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);
}

From source file:org.apache.flume.channel.file.TestFileChannelRestart.java

private void doTestIncompleteCheckpoint(boolean backup) throws Exception {
    Map<String, String> overrides = Maps.newHashMap();
    overrides.put(FileChannelConfiguration.USE_DUAL_CHECKPOINTS, String.valueOf(backup));
    channel = createFileChannel(overrides);
    channel.start();/*from   w ww . jav a2  s. c o m*/
    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_CHECKPOINT_MARKER * Serialization.SIZE_OF_LONG);
    writer.writeLong(EventQueueBackingStoreFile.CHECKPOINT_INCOMPLETE);
    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);
}

From source file:it.drwolf.ridire.session.async.JobDBDataUpdater.java

private String getJobStatus(String encodedJobName) throws HttpException, IOException, DocumentException {
    // back compatibility Heritrix 2
    if (encodedJobName.startsWith("completed-")) {
        return CrawlStatus.FINISHED.toString();
    }/*ww w.  j  a  v  a  2s  . c o  m*/
    File jobDir = new File(this.jobsDir + CrawlerManager.FILE_SEPARATOR + encodedJobName);
    String[] files = jobDir.list();
    if (files == null || files.length < 2) {
        return CrawlStatus.CREATED.toString();
    }
    String ret = CrawlStatus.CREATED.toString();
    RandomAccessFile progressStatistics = null;
    Calendar now = new GregorianCalendar();
    Date comparingDate = DateUtils.addDays(now.getTime(), -3);
    try {
        progressStatistics = new RandomAccessFile(
                this.jobsDir + CrawlerManager.FILE_SEPARATOR + encodedJobName + CrawlerManager.FILE_SEPARATOR
                        + "logs" + CrawlerManager.FILE_SEPARATOR + "progress-statistics.log",
                "r");
        if (progressStatistics != null) {
            progressStatistics.seek(Math.max(0, progressStatistics.length() - 3000));
            String line = progressStatistics.readLine();
            StringBuffer buffer = new StringBuffer();
            while (line != null) {
                buffer.append(line + "\n");
                line = progressStatistics.readLine();
            }
            String progressStatisticsContent = buffer.toString();
            Matcher m = this.progressStatisticsDatePattern.matcher(progressStatisticsContent);
            int start = 0;
            String lastDateString = "";
            while (m.find(start)) {
                start = m.end();
                lastDateString = m.group();
            }
            Date lastDate = this.progressStatisticsDateFormat.parse(lastDateString);
            if (!progressStatisticsContent.contains("CRAWL ENDED - Finished")
                    && lastDate.after(comparingDate)) {
                ret = CrawlStatus.RUNNING.toString();
            } else {
                ret = CrawlStatus.FINISHED.toString();
            }

        }
    } catch (FileNotFoundException e) {
        // TODO: handle exception
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (progressStatistics != null) {
            progressStatistics.close();
        }
    }
    // File crawlReport = new File(this.jobsDir + FILE_SEPARATOR
    // + encodedJobName + FILE_SEPARATOR + "reports" + FILE_SEPARATOR
    // + "crawl-report.txt");
    // if (crawlReport != null && crawlReport.canRead()) {
    // String crawlReportContent = FileUtils.readFileToString(crawlReport);
    // if (crawlReportContent.contains("crawl status: Finished")) {
    // ret = CrawlStatus.FINISHED.toString();
    // }
    // }
    return ret;
}