Example usage for java.io RandomAccessFile writeInt

List of usage examples for java.io RandomAccessFile writeInt

Introduction

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

Prototype

public final void writeInt(int v) throws IOException 

Source Link

Document

Writes an int to the file as four bytes, high byte first.

Usage

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

private static void appendTargetsToLogFile(File logFileName, IntrusiveList<CrawlTarget> list)
        throws IOException {

    LogFileHeader header = new LogFileHeader();

    boolean preExistingHeader = logFileName.exists();

    RandomAccessFile file = new RandomAccessFile(logFileName, "rw");

    try {//www .  j  a v a2  s  .  c o  m
        long headerOffset = 0;

        if (preExistingHeader) {

            headerOffset = readLogFileHeader(file, header);

            if (header._writePos == 0) {
                file.seek(headerOffset);
            } else {
                // seelk to appropriate write position 
                file.seek(header._writePos);
            }
        } else {
            headerOffset = writeLogFileHeader(file, header);
        }

        CustomByteArrayOutputStream bufferOutputStream = new CustomByteArrayOutputStream(1 << 17);
        DataOutputStream dataOutputStream = new DataOutputStream(bufferOutputStream);
        CRC32 crc = new CRC32();

        for (CrawlTarget target : list) {

            PersistentCrawlTarget persistentTarget = target.createPersistentTarget();

            bufferOutputStream.reset();
            // write to intermediate stream ... 
            persistentTarget.write(dataOutputStream);
            // and crc the data ... 
            crc.reset();
            crc.update(bufferOutputStream.getBuffer(), 0, bufferOutputStream.size());
            // write out length first 
            file.writeInt(bufferOutputStream.size());
            //crc next
            long computedValue = crc.getValue();
            //TODO: waste of space - write 32 bit values as long because having problems with java sign promotion rules during read...
            file.writeLong(computedValue);
            // and then the data 
            file.write(bufferOutputStream.getBuffer(), 0, bufferOutputStream.size());
        }

        // now update header ... 
        header._itemCount += list.size();
        header._writePos = file.getFilePointer();

        // now write out header anew ... 
        writeLogFileHeader(file, header);

    } finally {
        if (file != null) {
            file.close();
        }
    }
}