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.apache.hadoop.hdfs.server.namenode.TestEditLogFileInputStream.java

/**
 * Regression test for HDFS-8965 which verifies that
 * FSEditLogFileInputStream#scanOp verifies Op checksums.
 *//* w w  w .ja va2 s  . c o m*/
@Test(timeout = 60000)
public void testScanCorruptEditLog() throws Exception {
    Configuration conf = new Configuration();
    File editLog = new File(System.getProperty("test.build.data", "/tmp"), "testCorruptEditLog");

    LOG.debug("Creating test edit log file: " + editLog);
    EditLogFileOutputStream elos = new EditLogFileOutputStream(conf, editLog.getAbsoluteFile(), 8192);
    elos.create(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION);
    FSEditLogOp.OpInstanceCache cache = new FSEditLogOp.OpInstanceCache();
    FSEditLogOp.MkdirOp mkdirOp = FSEditLogOp.MkdirOp.getInstance(cache);
    mkdirOp.reset();
    mkdirOp.setRpcCallId(123);
    mkdirOp.setTransactionId(1);
    mkdirOp.setInodeId(789L);
    mkdirOp.setPath("/mydir");
    PermissionStatus perms = PermissionStatus.createImmutable("myuser", "mygroup",
            FsPermission.createImmutable((short) 0777));
    mkdirOp.setPermissionStatus(perms);
    elos.write(mkdirOp);
    mkdirOp.reset();
    mkdirOp.setRpcCallId(456);
    mkdirOp.setTransactionId(2);
    mkdirOp.setInodeId(123L);
    mkdirOp.setPath("/mydir2");
    perms = PermissionStatus.createImmutable("myuser", "mygroup", FsPermission.createImmutable((short) 0666));
    mkdirOp.setPermissionStatus(perms);
    elos.write(mkdirOp);
    elos.setReadyToFlush();
    elos.flushAndSync(false);
    elos.close();
    long fileLen = editLog.length();

    LOG.debug("Corrupting last 4 bytes of edit log file " + editLog + ", whose length is " + fileLen);
    RandomAccessFile rwf = new RandomAccessFile(editLog, "rw");
    rwf.seek(fileLen - 4);
    int b = rwf.readInt();
    rwf.seek(fileLen - 4);
    rwf.writeInt(b + 1);
    rwf.close();

    EditLogFileInputStream elis = new EditLogFileInputStream(editLog);
    Assert.assertEquals(NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION, elis.getVersion(true));
    Assert.assertEquals(1, elis.scanNextOp());
    LOG.debug("Read transaction 1 from " + editLog);
    try {
        elis.scanNextOp();
        Assert.fail("Expected scanNextOp to fail when op checksum was corrupt.");
    } catch (IOException e) {
        LOG.debug("Caught expected checksum error when reading corrupt " + "transaction 2", e);
        GenericTestUtils.assertExceptionContains("Transaction is corrupt.", e);
    }
    elis.close();
}

From source file:org.apache.jackrabbit.core.value.BLOBInTempFile.java

public int read(byte[] b, long position) throws IOException, RepositoryException {
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    try {/*  w  w  w  .j  a va 2  s.  co  m*/
        raf.seek(position);
        return raf.read(b);
    } finally {
        raf.close();
    }
}

From source file:com.thoughtworks.go.config.GoConfigFileWriter.java

public synchronized void writeToConfigXmlFile(String content) {
    FileChannel channel = null;//from   ww w.j av  a  2  s . c o  m
    FileOutputStream outputStream = null;
    FileLock lock = null;

    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw");
        channel = randomAccessFile.getChannel();
        lock = channel.lock();
        randomAccessFile.seek(0);
        randomAccessFile.setLength(0);
        outputStream = new FileOutputStream(randomAccessFile.getFD());

        IOUtils.write(content, outputStream, UTF_8);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (channel != null && lock != null) {
            try {
                lock.release();
                channel.close();
                IOUtils.closeQuietly(outputStream);
            } catch (IOException e) {
                LOGGER.error("Error occured when releasing file lock and closing file.", e);
            }
        }
    }
}

From source file:com.qubole.rubix.core.TestCachingInputStream.java

private void writeZeros(String filename, int start, int end) throws IOException {
    File file = new File(filename);
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    raf.seek(start);
    String s = "0";
    StandardCharsets.UTF_8.encode(s);
    for (int i = 0; i < (end - start); i++) {
        raf.writeBytes(s);/*from  www . ja  v a2s .  c  o m*/
    }
    raf.close();
}

From source file:com.ieasy.basic.util.file.FileUtils.java

/**
 * ??//from  w w  w .  j a v a 2 s  . c  om
 * 
 * @param fileName
 *            ??
 */
public static void readFileByRandomAccess(String fileName) {
    RandomAccessFile randomFile = null;
    try {
        System.out.println("??");
        // ????
        randomFile = new RandomAccessFile(fileName, "r");
        // 
        long fileLength = randomFile.length();
        // ?
        int beginIndex = (fileLength > 4) ? 4 : 0;
        // ?beginIndex?
        randomFile.seek(beginIndex);
        byte[] bytes = new byte[10];
        int byteread = 0;
        // 10?10
        // ?byteread
        while ((byteread = randomFile.read(bytes)) != -1) {
            System.out.write(bytes, 0, byteread);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (randomFile != null) {
            try {
                randomFile.close();
            } catch (IOException e1) {
            }
        }
    }
}

From source file:com.microsoft.azure.management.datalake.store.uploader.UploadMetadataGenerator.java

/**
 * Reads data from the given file into the given buffer, centered around the given file offset. The first half of the buffer will be
 * filled with data right before the given offset, while the remainder of the buffer will contain data right after it (of course, containing the byte at the given offset).
 * @param stream The stream to read from
 * @param buffer The buffer to read data into
 * @param fileReferenceOffset The offset to start reading from in the stream.
 * @return The number of bytes reads, which could be less than the length of the input buffer if we can't read due to the beginning or the end of the file.
 * @throws IOException Thrown if the stream being used is invalid or inaccessible.
 *//*from  ww w.j  av  a 2s.  c  om*/
private static int readIntoBufferAroundReference(RandomAccessFile stream, byte[] buffer,
        long fileReferenceOffset) throws IOException {
    int length = buffer.length;
    //calculate start offset
    long fileStartOffset = fileReferenceOffset - length / 2;

    if (fileStartOffset < 0) {
        //offset is less than zero, adjust it, as well as the length we want to read
        length += (int) fileStartOffset;
        fileStartOffset = 0;
        if (length <= 0) {
            return 0;
        }
    }

    if (fileStartOffset + length > stream.length()) {
        //startOffset + length is beyond the end of the stream, adjust the length accordingly
        length = (int) (stream.length() - fileStartOffset);
        if (length <= 0) {
            return 0;
        }
    }

    //read the appropriate block of the file into the buffer, using symmetry with respect to its midpoint
    // we always initiate a seek from the origin of the file.
    stream.seek(0);
    stream.seek(fileStartOffset);
    int bufferOffset = 0;
    while (bufferOffset < length) {
        int bytesRead = stream.read(buffer, bufferOffset, length - bufferOffset);
        bufferOffset += bytesRead;
    }
    return length;
}

From source file:ape.CorruptFileCommand.java

/**
 * This method is the actual method used to corrupt data/file
 *///from  w ww  .ja v a 2 s .c  o  m
public boolean corrupt(String corruptAddress) throws IOException {
    FileInputStream fin;
    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) {
        e.printStackTrace();
        return false;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(corruptAddress, "rw");
        try {
            raf.seek(offset);

            raf.write(buf, 0, count);
            raf.seek(0);
            raf.close();
        } catch (IOException e) {
            System.out.println("Corrupting file failed");
            Main.logger.info("Corrupting file failed");
            e.printStackTrace();
            Main.logger.info(e);
            return false;
        }

        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;
    }
}

From source file:com.baidu.terminator.manager.service.LogServiceImpl.java

@Override
public Log readLog(int linkId, long offset) throws IOException {
    String logFileLocation = LinkLogger.getLogFileLocation(linkId);
    FileUtils.createFile(logFileLocation);

    RandomAccessFile raf = null;
    List<String> lines = new ArrayList<String>();
    long length = 0;

    try {//from  www. j av a  2s  .c  o  m
        raf = new RandomAccessFile(logFileLocation, "r");
        raf.seek(offset);
        length = raf.length();

        long point = raf.getFilePointer();
        while (point < length) {
            String line = raf.readLine();
            String utf8Line = new String(line.getBytes("8859_1"), "utf-8");
            lines.add(utf8Line);

            if (point - offset >= MAX_READ_BYTES) {
                length = point;
                break;
            }
            point = raf.getFilePointer();
        }
    } finally {
        if (raf != null) {
            raf.close();
        }
    }

    Log log = new Log();
    log.setLogLocation(logFileLocation);
    log.setOffset(length);
    log.setContent(lines);
    return log;
}

From source file:de.erdesignerng.dialect.msaccess.MSAccessFileFormat.java

private static int findInFile(String aFileName, String aSearchFor) {
    int theBufferSize = 5242880; // 5MB
    boolean theSearchOn = true;
    String theStringBuffer;// www  . java  2 s  .co m
    int theOffset = 0;
    int theRead = theBufferSize;
    int thePosition;
    int theOverhead = aSearchFor.length() - 1;
    int theResult = -1;

    if (theBufferSize >= aSearchFor.length()) {
        try {
            File file = new File(aFileName);
            RandomAccessFile ra = new RandomAccessFile(aFileName, "r");
            byte[] theByteBuffer = new byte[theBufferSize];

            while ((theOffset < file.length()) && (theSearchOn) && (theRead == theBufferSize)) {
                theRead = ra.read(theByteBuffer);

                if (theRead >= 0) {
                    theStringBuffer = new String(theByteBuffer, 0, theRead);

                    thePosition = theStringBuffer.indexOf(aSearchFor);

                    if (thePosition >= 0) {
                        theResult = theOffset + thePosition;
                        theSearchOn = false;
                        LOGGER.debug(
                                "Found '" + aSearchFor + "' in '" + aFileName + "' at position " + theResult);
                    } else {
                        if (theRead == theBufferSize) {
                            theOffset += (theRead - theOverhead);
                            ra.seek(theOffset);
                        }
                    }
                }
            }

            ra.close();
        } catch (FileNotFoundException ex) {
            LOGGER.error("Cannot find database file " + aFileName, ex);
        } catch (IOException ex) {
            LOGGER.error("Cannot read database file " + aFileName, ex);
        }
    } else {
        throw new RuntimeException("The string to find is too long. Only strings of lenght up to "
                + theBufferSize + " can be found!");
    }

    return theResult;
}

From source file:org.apache.sling.commons.log.logback.internal.Tailer.java

/**
 * Read new lines. Code below is taken from org.apache.commons.io.input.Tailer
 *
 * @throws java.io.IOException if an I/O error occurs.
 * @param startPos position in file from where to start reading
 *///from  w w w .j ava2  s  .c  om
private void readLines(RandomAccessFile file, long startPos) throws IOException {
    StringBuilder sb = new StringBuilder();

    file.seek(startPos);
    int num;
    boolean seenCR = false;
    while (((num = file.read(buffer)) != -1)) {
        for (int i = 0; i < num; i++) {
            byte ch = buffer[i];
            switch (ch) {
            case '\n':
                seenCR = false; // swallow CR before LF
                listener.handle(sb.toString());
                sb.setLength(0);
                break;
            case '\r':
                if (seenCR) {
                    sb.append('\r');
                }
                seenCR = true;
                break;
            default:
                if (seenCR) {
                    seenCR = false; // swallow final CR
                    listener.handle(sb.toString());
                    sb.setLength(0);
                }
                sb.append((char) ch); // add character, not its ascii value
            }
        }
    }

    //Drain the left over part
    if (sb.length() != 0) {
        listener.handle(sb.toString());
    }
}