Example usage for java.io RandomAccessFile close

List of usage examples for java.io RandomAccessFile close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this random access file stream and releases any system resources associated with the stream.

Usage

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void dumpSpeed2Helper(File file) throws Exception {
    int WARMUP = 2;
    int RUNS = 3;
    LineReader lr = new LineReader(file, "r");
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    for (int i = 0; i < WARMUP; i++) {
        dumpSpeed2Helper(lr, raf, true);
    }//  ww  w  .  j a va  2 s. co m
    for (int i = 0; i < RUNS; i++) {
        dumpSpeed2Helper(lr, raf, false);
    }
    lr.close();
    raf.close();
}

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void testReadByte() throws Exception {
    RandomAccessFile ra = new RandomAccessFile(logfile, "r");
    LineReader lr = new LineReader(logfile, "r");
    int counter = 1;
    while (!lr.eof()) {
        assertEquals("Byte #" + counter++ + " should be read correct", ra.readByte(), lr.readByte());
    }//  w w w. j  a  v a 2s  .  co m
    ra.close();
    lr.close();
}

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   www.ja  v a2 s .  c o  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:eu.stratosphere.nephele.services.iomanager.IOManagerPerformanceBenchmark.java

@SuppressWarnings("resource")
private final void speedTestNIO(int bufferSize, boolean direct) throws IOException {
    final Channel.ID tmpChannel = ioManager.createChannel();

    File tempFile = null;//ww w.  ja v  a  2s. c  o m
    FileChannel fs = null;

    try {
        tempFile = new File(tmpChannel.getPath());

        RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
        fs = raf.getChannel();

        ByteBuffer buf = direct ? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize);

        long writeStart = System.currentTimeMillis();

        int valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            if (buf.remaining() < 4) {
                buf.flip();
                fs.write(buf);
                buf.clear();
            }
            buf.putInt(valsLeft);
        }

        if (buf.position() > 0) {
            buf.flip();
            fs.write(buf);
        }

        fs.close();
        raf.close();
        fs = null;

        long writeElapsed = System.currentTimeMillis() - writeStart;

        // ----------------------------------------------------------------

        raf = new RandomAccessFile(tempFile, "r");
        fs = raf.getChannel();
        buf.clear();

        long readStart = System.currentTimeMillis();

        fs.read(buf);
        buf.flip();

        valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            if (buf.remaining() < 4) {
                buf.compact();
                fs.read(buf);
                buf.flip();
            }
            if (buf.getInt() != valsLeft) {
                throw new IOException();
            }
        }

        fs.close();
        raf.close();

        long readElapsed = System.currentTimeMillis() - readStart;

        LOG.info("NIO Channel with buffer " + bufferSize + ": write " + writeElapsed + " msecs, read "
                + readElapsed + " msecs.");
    } finally {
        // close if possible
        if (fs != null) {
            fs.close();
            fs = null;
        }
        // try to delete the file
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:com.tcl.lzhang1.mymusic.MusicUtil.java

/**
 * get the music info// ww  w .jav  a2  s  .co  m
 * 
 * @param musicFile
 * @return
 */
public static SongModel getMusicInfo(File musicFile) {
    SongModel model = new SongModel();
    // retrun null if music file is null or is or directory
    if (musicFile == null || !musicFile.isFile()) {
        return null;
    }

    byte[] buf = new byte[128];
    try {
        Log.d(LOG_TAG, "process music file{" + musicFile.getAbsolutePath() + "}");
        // tag_v1
        RandomAccessFile music = new RandomAccessFile(musicFile, "r");

        music.seek(music.length() - 128);
        music.read(buf);// read tag to buffer
        // tag_v2
        byte[] header = new byte[10];
        music.seek(0);
        music.read(header, 0, 10);
        // if ("ID3".equalsIgnoreCase(new String(header, 0, 3))) {
        // int ID3V2_frame_size = (int) (header[6] & 0x7F) * 0x200000
        // | (int) (header[7] & 0x7F) * 0x400
        // | (int) (header[8] & 0x7F) * 0x80
        // | (int) (header[9] & 0x7F);
        // byte[] FrameHeader = new byte[4];
        // music.seek(ID3V2_frame_size + 10);
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, ID3V2_frame_size, musicFile);
        // } else {
        // byte[] FrameHeader = new byte[4];
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, 0, musicFile);
        // }

        music.close();// close file
        // check length
        // if (buf.length != 128) {
        // throw new
        // ErrorMusicLength(String.format("error music info length, length is:%i",
        // buf.length));
        // }
        //
        // if (!"TAG".equalsIgnoreCase(new String(buf, 0, 3))) {
        // throw new UnknownTagException("unknown tag exception");
        // }
        String songName = null;
        // try {
        // songName = new String(buf, 3, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // e.printStackTrace();
        // songName = new String(buf, 3, 30).trim();
        // }
        String singerName = "";
        // try {
        // singerName = new String(buf, 33, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // singerName = new String(buf, 33, 30).trim();
        // }
        String ablum = "";
        // try {
        // ablum = new String(buf, 63, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // ablum = new String(buf, 63, 30).trim();
        // }
        String year = "";
        // try {
        // year = new String(buf, 93, 4, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // year = new String(buf, 93, 4).trim();
        // // TODO: handle exception
        // }

        String reamrk = "";
        ContentResolver contentResolver = sContext.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, "_data=?",
                new String[] { musicFile.getAbsolutePath() }, null);
        cursor.moveToFirst();
        if (cursor != null && cursor.getCount() != 0) {
            try {
                if (TextUtils.isEmpty(songName)) {
                    songName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE));
                    singerName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST));
                    ablum = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM));
                    year = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.YEAR));
                }

                long secs = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION));
                model.setTime(secs);
                secs /= 1000;
                model.setHours((int) secs / 3600);
                model.setMinutes(((int) secs % 3600) / 60);
                model.setSeconds(((int) secs % 3600) % 60);
                cursor.close();
            } catch (CursorIndexOutOfBoundsException e) {
                // TODO: handle exception
                if (null != cursor) {
                    cursor.close();
                    cursor = null;
                }
                Log.d(LOG_TAG, "CursorIndexOutOfBoundsException:" + e.getMessage());
                try {
                    songName = new String(buf, 3, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e0) {
                    // TODO: handle exception
                    e.printStackTrace();
                    songName = new String(buf, 3, 30).trim();
                }
                try {
                    singerName = new String(buf, 33, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e1) {
                    // TODO: handle exception
                    singerName = new String(buf, 33, 30).trim();
                }
                try {
                    ablum = new String(buf, 63, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e2) {
                    // TODO: handle exception
                    ablum = new String(buf, 63, 30).trim();
                }
                try {
                    year = new String(buf, 93, 4, "gbk").trim();
                } catch (UnsupportedEncodingException e3) {
                    year = new String(buf, 93, 4).trim();
                    // TODO: handle exception
                }

                try {
                    reamrk = new String(buf, 97, 28, "gbk").trim();
                } catch (UnsupportedEncodingException e4) {
                    // TODO: handle exception
                    reamrk = new String(buf, 97, 28).trim();
                }

            }
        }

        //

        // get the time len

        model.setSongName(songName);
        model.setSingerName(singerName);
        model.setAblumName(ablum);
        model.setFile(musicFile.getAbsolutePath());
        model.setRemark("");
        Log.d(LOG_TAG, String.format("scaned music file[%s],album name[%s],song name[%s],singer name[%s]",
                model.getFile(), model.getAblumName(), model.getSingerName(), model.getSingerName()));

        mSongs.add(model);

        return model;
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return model;
}

From source file:com.landenlabs.all_devtool.ConsoleFragment.java

/**
 * Gets total system cpu usage (not just this app)
 * @return//from ww w.ja v  a  2  s . co  m
 */
private float getCpuUsage() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();

        String[] toks = load.split(" ");

        long idle1 = Long.parseLong(toks[5]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(360);
        } catch (Exception e) {
        }

        reader.seek(0);
        load = reader.readLine();
        reader.close();

        toks = load.split(" ");

        long idle2 = Long.parseLong(toks[5]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float) (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 0;
}

From source file:com.teletalk.jserver.util.filedb.LowLevelFileDBTest.java

/**
 * testCorruptData//from ww w  . ja  v a  2s.c  o m
 */
public void testCorruptData() {
    logger.info("BEGIN testCorruptData.");

    String fileNameBase = BASE_PATH + "fileDBCorrupt/fileDBCorrupt";
    new File(fileNameBase).mkdirs();

    try {
        new File(fileNameBase + ".idx").delete();
        new File(fileNameBase + ".dat").delete();

        final int allocationUnitSize = 10;
        final int blockSize = (allocationUnitSize + DefaultDataFile.BLOCK_HEADER_SIZE
                + DefaultDataFile.BLOCK_FOOTER_SIZE);

        LowLevelFileDB lowLevelFileDB = new LowLevelFileDB("LowLevelFileDB", fileNameBase, blockSize, 2, 2,
                LowLevelFileDB.READ_WRITE_MODE);

        String dataString = "DATA123456";
        byte[] data = dataString.getBytes();
        lowLevelFileDB.insertItem("key1", data);
        lowLevelFileDB.insertItem("key2", data);
        lowLevelFileDB.insertItem("key3", data);

        lowLevelFileDB.closeFileDB();

        byte[] corruptHeader = new byte[DefaultDataFile.BLOCK_HEADER_SIZE];

        // Destroy header of first data block
        RandomAccessFile randomAccessFile = new RandomAccessFile(fileNameBase + ".dat", "rw");
        randomAccessFile.seek(DefaultDataFile.DATA_FILE_HEADER_SIZE);
        randomAccessFile.write(corruptHeader);
        randomAccessFile.close();

        // Destroy header of second index block
        randomAccessFile = new RandomAccessFile(fileNameBase + ".idx", "rw");
        randomAccessFile.seek(DefaultDataFile.DATA_FILE_HEADER_SIZE + lowLevelFileDB.getIndexFileBlockSize());
        randomAccessFile.write(corruptHeader);
        randomAccessFile.close();

        // Reopen
        lowLevelFileDB = new LowLevelFileDB("LowLevelFileDB", fileNameBase, 20, 2, 2,
                LowLevelFileDB.READ_WRITE_MODE);

        byte[] readData = lowLevelFileDB.getItem("key1");
        if (readData != null)
            super.fail("Item with key 'key1' shouldn't exist!");
        readData = lowLevelFileDB.getItem("key2");
        if (readData != null)
            super.fail("Item with key 'key2' shouldn't exist!");
        readData = lowLevelFileDB.getItem("key3");
        if (readData == null)
            super.fail("Item with key 'key3' wasn't found!");
        if (!dataString.equals(new String(readData)))
            super.fail("Data for item with key 'key3' was invalid!");

        lowLevelFileDB.closeFileDB();

        FileDeletor.delete("fileDBCorrupt");
        new File(fileNameBase + ".idx").delete();
        new File(fileNameBase + ".dat").delete();
    } catch (Exception e) {
        e.printStackTrace();
        super.fail("Error - " + e);
    }

    logger.info("END testCorruptData.");
}

From source file:com.datatorrent.flume.storage.HDFSStorageTest.java

@Test
public void testCleanup() throws IOException {
    RandomAccessFile r = new RandomAccessFile(testMeta.testFile, "r");
    r.seek(0);/*ww w  .  j a  va 2  s .  co  m*/
    byte[] b = r.readLine().getBytes();
    storage.store(new Slice(b, 0, b.length));
    byte[] val = storage.store(new Slice(b, 0, b.length));
    storage.flush();
    storage.clean(val);
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);
    boolean exists = fs.exists(new Path(STORAGE_DIRECTORY + "/" + "0"));
    Assert.assertEquals("file should not exist", false, exists);
    r.close();
}

From source file:ape.CorruptCommand.java

/**
 * This method is the implementation of the corrupt function.
 * Given an address, it corrupts the file in the given address
 *//*  w  w w.j a v a2  s  . c o  m*/
public boolean corrupt(String corruptAddress) throws IOException {
    // Trying to get a random HDFS block file
    if (Main.VERBOSE) {
        System.out.println("Trying to get a random HDFS block file");
    }
    if (corruptAddress == null) {
        corruptAddress = getCorruptAddress();
    }

    // If the above statement failed to set corruptAddress then there was a failure
    if (corruptAddress == null) {
        System.out.println("Could not get a random HDFS block file");
        Main.logger.info("Could not get a random HDFS block file");
        return false;
    }

    byte[] buf;
    int count;

    try {
        RandomAccessFile tmp = new RandomAccessFile(corruptAddress, "rw");
        tmp.seek(offset);
        if (size <= 0) {
            System.out.println("ERROR: The size parameter must be positive");
            Main.logger.info("ERROR: The size parameter must be positive");
            return false;
        }

        buf = new byte[size];

        count = 0;
        if ((count = tmp.read(buf, 0, size)) == -1) {
            System.out.println("The file chosen is smaller than the corruption size (" + size + " bytes)");
            Main.logger.info("The file chosen is smaller than the corruption size (" + size + " bytes)");
            return false;
        }

        for (int i = 0; i < count; i++) {
            buf[i] = 0x3;
        }

        tmp.seek(0);
        tmp.close();
    } catch (FileNotFoundException e1) {
        System.out.println("Cannot open the file on the path given");
        Main.logger.info("Cannot open the file on the path given");
        e1.printStackTrace();
        Main.logger.info(e1);
        return false;
    } catch (IOException e) {
        System.out.println("Corrupting file failed");
        Main.logger.info("Corrupting file failed");
        e.printStackTrace();
        Main.logger.info(e);
        return false;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(corruptAddress, "rw");
        raf.seek(offset);
        raf.write(buf, 0, count);
        raf.seek(0);
        raf.close();

        return true;
    } catch (FileNotFoundException e1) {
        System.out.println("Cannot open the file on the path: " + corruptAddress);
        Main.logger.info("Cannot open the file on the path: " + corruptAddress);
        e1.printStackTrace();
        Main.logger.info(e1);
        return false;
    } catch (IOException e) {
        System.out.println("Corrupting file failed");
        Main.logger.info("Corrupting file failed");
        e.printStackTrace();
        Main.logger.info(e);
        return false;
    }
}

From source file:dk.netarkivet.common.utils.FileUtils.java

/**
 * Read the last line in a file. Note this method is not UTF-8 safe.
 *
 * @param file input file to read last line from.
 * @return The last line in the file (ending newline is irrelevant),
 * returns an empty string if file is empty.
 * @throws ArgumentNotValid on null argument, or file is not a readable
 * file./*from   w ww  .  j  a  v a  2  s  .com*/
 * @throws IOFailure on IO trouble reading file.
 */
public static String readLastLine(File file) {
    ArgumentNotValid.checkNotNull(file, "File file");
    if (!file.isFile() || !file.canRead()) {
        final String errMsg = "File '" + file.getAbsolutePath() + "' is not a readable file.";
        log.warn(errMsg);
        throw new ArgumentNotValid(errMsg);
    }
    if (file.length() == 0) {
        return "";
    }
    RandomAccessFile rafile = null;
    try {
        rafile = new RandomAccessFile(file, "r");
        //seek to byte one before end of file (remember we know the file is
        // not empty) - this ensures that an ending newline is not read
        rafile.seek(rafile.length() - 2);
        //now search to the last linebreak, or beginning of file
        while (rafile.getFilePointer() != 0 && rafile.read() != '\n') {
            //search back two, because we just searched forward one to find
            //newline
            rafile.seek(rafile.getFilePointer() - 2);
        }
        return rafile.readLine();
    } catch (IOException e) {
        final String errMsg = "Unable to access file '" + file.getAbsolutePath() + "'";
        log.warn(errMsg, e);
        throw new IOFailure(errMsg, e);
    } finally {
        try {
            if (rafile != null) {
                rafile.close();
            }
        } catch (IOException e) {
            log.debug("Unable to close file '" + file.getAbsolutePath() + "' after reading", e);
        }
    }
}