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:cerrla.Performance.java

/**
 * Reads a raw numerical performance file and stores the values as
 * accessible private values.//from ww  w  .  j  a v a2s  .co  m
 * 
 * @param perfFile
 *            The performance file to read.
 * @return True if the file was read successfully, false otherwise.
 */
public static boolean readRawPerformanceFile(File perfFile, boolean byEpisode) throws Exception {
    if (Config.getInstance().getGeneratorFile() == null) {
        // First, read the last line of the normal file for the time
        RandomAccessFile raf = new RandomAccessFile(perfFile, "r");
        long pos = perfFile.length() - 1;
        StringBuffer line = new StringBuffer();
        char c;
        boolean foundIt = false;
        do {
            raf.seek(pos);
            c = (char) raf.read();
            foundIt |= Character.isDigit(c);
            line.append(c);
            pos--;
        } while (!foundIt || Character.isDigit(c) || c == ':');
        raf.close();
        String time = line.reverse().toString().trim();
        String[] timeSplit = time.split(":");
        runTime_ = (Long.parseLong(timeSplit[2]) + 60 * Long.parseLong(timeSplit[1])
                + 3600 * Long.parseLong(timeSplit[0])) * 1000;
    }

    if (Config.getInstance().getGeneratorFile() == null)
        perfFile = new File(perfFile.getPath() + "raw");
    else
        perfFile = new File(perfFile.getPath() + "greedy");
    performanceMap_ = new TreeMap<Integer, Float[]>();
    FileReader reader = new FileReader(perfFile);
    BufferedReader buf = new BufferedReader(reader);

    // For every value within the performance file
    String input = null;
    Float[] prevPerfs = null;
    while ((input = buf.readLine()) != null) {
        String[] vals = input.split("\t");
        if (vals[PerformanceDetails.EPISODE.ordinal()].equals("Episode"))
            continue;

        Float[] perfs = new Float[PerformanceDetails.values().length];
        int episode = 0;
        for (PerformanceDetails detail : PerformanceDetails.values()) {
            if (vals.length > detail.ordinal()) {
                if (!vals[detail.ordinal()].equals("null"))
                    perfs[detail.ordinal()] = Float.parseFloat(vals[detail.ordinal()]);
                else if (detail.equals(PerformanceDetails.ELITEMEAN)
                        && !vals[PerformanceDetails.ELITEMAX.ordinal()].equals("null"))
                    perfs[detail.ordinal()] = Float.parseFloat(vals[PerformanceDetails.ELITEMAX.ordinal()]);
                else if (detail.equals(PerformanceDetails.ELITEMEAN)
                        || detail.equals(PerformanceDetails.ELITEMAX))
                    perfs[detail.ordinal()] = Float.parseFloat(vals[PerformanceDetails.MEAN.ordinal()]);
                else if (prevPerfs != null)
                    perfs[detail.ordinal()] = prevPerfs[detail.ordinal()];
            }

            if (detail.equals(PerformanceDetails.EPISODE))
                episode = perfs[detail.ordinal()].intValue();
        }

        performanceMap_.put(episode, perfs);
        prevPerfs = perfs;
    }

    buf.close();
    reader.close();

    return true;
}

From source file:net.yacy.document.importer.MediawikiImporter.java

public static byte[] read(final File f, final long start, final int len) {
    final byte[] b = new byte[len];
    RandomAccessFile raf = null;
    try {//from www .j  av  a 2  s .  c o  m
        raf = new RandomAccessFile(f, "r");
        raf.seek(start);
        raf.read(b);
    } catch (final IOException e) {
        ConcurrentLog.logException(e);
        return null;
    } finally {
        if (raf != null)
            try {
                raf.close();
                try {
                    raf.getChannel().close();
                } catch (final IOException e) {
                }
            } catch (final IOException e) {
            }
    }
    return b;
}

From source file:phex.util.FileUtils.java

/**
 * Appends the fileToAppend on the destination file. The file that is appended
 * will be removed afterwards./*  ww  w  . j  a  v  a  2s .c  om*/
 *
 * @throws IOException in case an IO operation fails
 */
public static void appendFile(File destination, File fileToAppend) throws IOException {
    long destFileLength = destination.length();
    long appendFileLength = fileToAppend.length();
    // open files
    FileInputStream inStream = new FileInputStream(fileToAppend);
    try {
        RandomAccessFile destFile = new RandomAccessFile(destination, "rwd");
        try {
            // extend file length... this causes dramatical performance boost since
            // contents is streamed into already freed space.
            destFile.setLength(destFileLength + appendFileLength);
            destFile.seek(destFileLength);
            byte[] buffer = new byte[(int) Math.min(BUFFER_LENGTH, appendFileLength)];
            int length;
            while (-1 != (length = inStream.read(buffer))) {
                long start2 = System.currentTimeMillis();
                destFile.write(buffer, 0, length);
                long end2 = System.currentTimeMillis();
                try {
                    Thread.sleep((end2 - start2) * 2);
                } catch (InterruptedException exp) {
                    // reset interrupted flag
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        } finally {
            destFile.close();
            IOUtil.closeQuietly(destFile);
        }
    } finally {
        IOUtil.closeQuietly(inStream);
    }

    FileUtils.deleteFileMultiFallback(fileToAppend);
}

From source file:org.apache.hadoop.io.nativeio.NativeIO2.java

/**
 * 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.// w  w  w . j  ava  2  s .  c om
 */
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 = NativeIO2.Windows.createFile(
                f.getAbsolutePath(), NativeIO2.Windows.GENERIC_READ, NativeIO2.Windows.FILE_SHARE_READ
                        | NativeIO2.Windows.FILE_SHARE_WRITE | NativeIO2.Windows.FILE_SHARE_DELETE,
                NativeIO2.Windows.OPEN_EXISTING);
        if (seekOffset > 0)
            NativeIO2.Windows.setFilePointer(fd, seekOffset, NativeIO2.Windows.FILE_BEGIN);
        return new FileInputStream(fd);
    }
}

From source file:org.srlutils.Files.java

/**
 * wrapper for RandomAccessFile.read()//  ww w  .  java  2 s .  co m
 * read len bytes from filename at position, filling bites starting at offset
 * if multiple exceptions are encountered (eg due to close() failing) throws the first only
 * @param bites if null, allocate a new array and read all available bytes
 * @param len if negative, fill bites
 * @return the byte array and number of bytes read
 * @throws RuntimeException wrapping any exceptions
 */
public static ReadInfo readbytes(String filename, long position, byte[] bites, int offset, int len) {
    ReadInfo read = new ReadInfo();
    RandomAccessFile fid = null;
    RuntimeException rte = null;
    try {
        String mode = "r";
        // fixme:memleak -- looks like fid is leaked ...
        fid = new RandomAccessFile(filename, mode);
        if (bites == null) {
            long size = fid.length() - position;
            if (size + offset > Integer.MAX_VALUE)
                throw new Exception(String.format(
                        "attempt to read the entirity of file '%s', size %d, is too large", filename, len));
            len = (int) size;
            bites = new byte[len + offset];
        }
        if (len < 0)
            len = bites.length - offset;
        fid.seek(position);
        read.num = fid.read(bites, offset, len);
        read.bytes = bites;
        return read;
    } catch (Exception ex) {
        rte = rte(ex, "failed to read string from file: %s", filename);
        throw rte;
    } finally {
        if (rte == null)
            rteClose(fid);
        else
            tryClose(fid);
    }
}

From source file:com.buaa.cfs.io.nativeio.NativeIO.java

/**
 * 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.
 *//*ww w  . ja  v  a2  s. c om*/
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);
    }
}

From source file:net.iharding.utils.FileUtils.java

/**   
 * RandomAccessFile   //from w  w  w.  j ava 2  s  . c o m
 *    
 * @param fileName ??   
 * @param content    
 */
public static void appendFile(String filePath, String content) {
    RandomAccessFile randomFile = null;
    try {
        // ???     
        randomFile = new RandomAccessFile(filePath, "rw");
        //      
        long fileLength = randomFile.length();
        //      
        randomFile.seek(fileLength);
        randomFile.writeUTF(content);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (randomFile != null) {
            try {
                randomFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.hdsfed.cometapi.HCPClient.java

/**
 * Copy the given byte range of the given input to the given output.
 * @param input The input to copy the given range to the given output for.
 * @param output The output to copy the given range from the given input for.
 * @param start Start of the byte range.
 * @param length Length of the byte range.
 * @throws IOException If something fails at I/O level.
 *//*from   w  w w .j a  va  2  s. c o m*/
public static void FileToOutputStream(RandomAccessFile input, OutputStream output, long start, long length)
        throws IOException {
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    int read;

    if (input.length() == length) {
        // Write full range.
        while ((read = input.read(buffer)) > 0) {
            output.write(buffer, 0, read);
        }
    } else {
        // Write partial range.
        input.seek(start);
        long toRead = length;

        while ((read = input.read(buffer)) > 0) {
            if ((toRead -= read) > 0) {
                output.write(buffer, 0, read);
            } else {
                output.write(buffer, 0, (int) toRead + read);
                break;
            }
        }
    }
}

From source file:org.commoncrawl.service.crawler.CrawlSegmentLog.java

public static void writeHeader(File logFilePath, int recordCount) throws IOException {
    RandomAccessFile stream = new RandomAccessFile(logFilePath, "rw");
    try {// w ww. ja  v  a2  s . c om
        stream.seek(0);
        stream.writeInt(LogFileHeaderBytes);
        stream.writeInt(recordCount);
    } finally {
        // stream.getFD().sync();
        stream.close();
    }
}

From source file:org.apache.hadoop.hdfs.TestRaidDfs.java

public static void corruptBlock(Path file, Block blockNum, int numDataNodes, long offset,
        MiniDFSCluster cluster) throws IOException {
    long id = blockNum.getBlockId();

    // Now deliberately remove/truncate data blocks from the block.
    //// ww  w . ja v a2  s .  c o  m
    for (int i = 0; i < numDataNodes; i++) {
        File[] dirs = getDataNodeDirs(i, cluster);

        for (int j = 0; j < dirs.length; j++) {
            File[] blocks = dirs[j].listFiles();
            assertTrue("Blocks do not exist in data-dir", (blocks != null) && (blocks.length >= 0));
            for (int idx = 0; idx < blocks.length; idx++) {
                if (blocks[idx].getName().startsWith("blk_" + id) && !blocks[idx].getName().endsWith(".meta")) {
                    // Corrupt
                    File f = blocks[idx];
                    RandomAccessFile raf = new RandomAccessFile(f, "rw");
                    raf.seek(offset);
                    int data = raf.readInt();
                    raf.seek(offset);
                    raf.writeInt(data + 1);
                    LOG.info("Corrupted block " + blocks[idx]);
                }
            }
        }
    }
}