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:FileBaseDataMap.java

private long getLinePoint(String key, RandomAccessFile raf) throws Exception {

    long line = -1;
    long lineCount = 0L;

    byte[] keyBytes = key.getBytes();
    byte[] equalKeyBytes = new byte[keyBytes.length + 1];
    byte[] lineBufs = new byte[this.getDataSize];
    boolean matchFlg = true;

    // ???/*w w w  .ja  v a  2  s.c o  m*/
    for (int idx = 0; idx < keyBytes.length; idx++) {
        equalKeyBytes[idx] = keyBytes[idx];
    }

    equalKeyBytes[equalKeyBytes.length - 1] = 38;

    try {

        raf.seek(0);
        int readLen = -1;
        while ((readLen = raf.read(lineBufs)) != -1) {

            matchFlg = true;

            int loop = readLen / lineDataSize;

            for (int loopIdx = 0; loopIdx < loop; loopIdx++) {

                int assist = (lineDataSize * loopIdx);

                matchFlg = true;
                if (equalKeyBytes[equalKeyBytes.length - 1] == lineBufs[assist + (equalKeyBytes.length - 1)]) {
                    for (int i = 0; i < equalKeyBytes.length; i++) {
                        if (equalKeyBytes[i] != lineBufs[assist + i]) {
                            matchFlg = false;
                            break;
                        }
                    }
                } else {
                    matchFlg = false;
                }

                // ???????
                if (matchFlg) {
                    line = lineCount;
                    break;
                }
                lineCount++;
            }
            if (matchFlg)
                break;
        }

    } catch (IOException ie) {
        throw ie;
    } catch (Exception e) {
        throw e;
    }
    return line;
}

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

private static long writeLogFileHeader(RandomAccessFile file, LogFileHeader header) throws IOException {

    // set the position at zero .. 
    file.seek(0);
    // and write header to disk ... 
    header.writeHeader(file);/*from   w w w. j  ava  2 s.c o m*/

    //took sync out because it was becoming a sever bottleneck
    // file.getFD().sync();

    return file.getFilePointer();
}

From source file:cern.acet.tracing.input.file.tailer.PositionTailer.java

/**
 * Read new lines./*from   w w w. ja v  a  2 s . c  o  m*/
 *
 * @param reader The file to read
 * @return The new position after the lines have been read
 * @throws java.io.IOException if an I/O error occurs.
 */
private long readLines(RandomAccessFile reader) throws IOException {
    StringBuilder sb = new StringBuilder();

    long pos = reader.getFilePointer();
    long rePos = pos; // position to re-read

    int num;
    boolean seenCR = false;
    while (run && ((num = reader.read(inbuf)) != -1)) {
        for (int i = 0; i < num; i++) {
            byte ch = inbuf[i];
            switch (ch) {
            case '\n':
                seenCR = false; // swallow CR before LF
                listener.handle(sb.toString());
                sb.setLength(0);
                rePos = pos + i + 1;
                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);
                    rePos = pos + i + 1;
                }
                sb.append((char) ch); // add character, not its ascii value
            }
        }

        pos = reader.getFilePointer();
    }

    reader.seek(rePos); // Ensure we can re-read if necessary
    listener.positionUpdated(pos);
    return rePos;
}

From source file:com.hly.component.download.DownloadTransaction.java

public void run() {
    // TODO ?Daemon
    InputStream is = null;/*  w w  w  .  java  2  s. c om*/
    HttpURLConnection conn = null;
    RandomAccessFile randomFile = null;
    File tmpFile = null;
    try {
        // ?uri
        tmpFile = new File(mTempLocalUri);
        File parentFile = tmpFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        if (!tmpFile.exists()) {
            tmpFile.createNewFile();
        }
        randomFile = new RandomAccessFile(mTempLocalUri, "rw");
        long fileLength = randomFile.length();
        completeSize = fileLength;

        if (isCancel) {
            return;
        }
        String connUrl = mUri;
        // ?uri????
        // getRedirectUrl(connUrl);
        if (!T.ckIsEmpty(mRedirectUri)) {
            connUrl = mRedirectUri;
        }
        conn = getHttpConnetion(connUrl);
        conn.setRequestProperty("range", "bytes=" + fileLength + "-");
        conn.connect();

        int contentLength = conn.getContentLength();
        totalSize = completeSize + contentLength;
        if (contentLength == -1 || contentLength > 0) {
            //    
            randomFile.seek(fileLength);
            byte[] buffer = new byte[8192];
            is = conn.getInputStream();
            int length = -1;
            while ((length = is.read(buffer)) != -1) {
                if (isCancel) {
                    return;
                }
                randomFile.write(buffer, 0, length);
                completeSize += length;
                notifyProgress(length);
            }
        }
        mTransactionState.setState(TransactionState.SUCCESS);
    } catch (Throwable t) {
        Log.w(TAG, Log.getStackTraceString(t));
    } finally {
        isRunning = false;
        isCancel = false;
        try {
            if (randomFile != null) {
                randomFile.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            conn.disconnect();
        }

        if (mTransactionState.getState() != TransactionState.SUCCESS) {
            mTransactionState.setState(TransactionState.FAILED);
            Log.e(TAG, "Delivery failed.");
        } else {
            if (tmpFile == null) {
                mTransactionState.setState(TransactionState.FAILED);
            } else {
                File localFile = new File(this.mLocalUri);
                boolean flag = tmpFile.renameTo(localFile);
                if (flag) {
                    Log.d(TAG, "rename pic succ" + this.mLocalUri);
                } else {
                    mTransactionState.setState(TransactionState.FAILED);
                    Log.d(TAG, "rename pic failed" + this.mLocalUri);
                }
            }
        }
        notifyObservers();
    }
}

From source file:MSUmpire.SpectrumParser.mzXMLParser.java

private List<MzXMLthreadUnit> ParseScans(final BitSet IncludedScans) {
    List<MzXMLthreadUnit> ScanList = new ArrayList<>();
    ArrayList<ForkJoinTask<?>> futures = new ArrayList<>();
    final ForkJoinPool fjp = new ForkJoinPool(NoCPUs);
    Iterator<Entry<Integer, Long>> iter = ScanIndex.entrySet().iterator();
    Entry<Integer, Long> ent = iter.next();
    long currentIdx = ent.getValue();
    int nextScanNo = ent.getKey();
    final RandomAccessFile fileHandler;
    try {//from w w  w  .jav  a 2 s  . com
        fileHandler = new RandomAccessFile(filename, "r");
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
    byte[] buffer = new byte[1 << 10];
    if (step == -1)
        step = fjp.getParallelism() * 32;
    while (iter.hasNext()) {
        ent = iter.next();
        long startposition = currentIdx;
        long nexposition = ent.getValue();
        int currentScanNo = nextScanNo;
        nextScanNo = ent.getKey();
        currentIdx = nexposition;

        if (IncludedScans.get(currentScanNo)) {
            try {
                final int bufsize = (int) (nexposition - startposition);
                if (buffer.length < bufsize)
                    buffer = new byte[Math.max(bufsize, buffer.length << 1)];
                //                    byte[] buffer = new byte[bufsize];
                //                    RandomAccessFile fileHandler = new RandomAccessFile(filename, "r");
                fileHandler.seek(startposition);
                fileHandler.read(buffer, 0, bufsize);
                //                    fileHandler.close();
                //                    String xmltext = new String(buffer);
                String xmltext = new String(buffer, 0, bufsize, StandardCharsets.ISO_8859_1);
                if (ent.getKey() == Integer.MAX_VALUE) {
                    xmltext = xmltext.replaceAll("</msRun>", "");
                }
                boolean ReadPeak = true;
                final MzXMLthreadUnit unit = new MzXMLthreadUnit(xmltext, parameter, datatype, ReadPeak);
                futures.add(fjp.submit(unit));
                ScanList.add(unit);

                if ((ScanList.size() % step) == 0) {
                    futures.get(futures.size() - step).get();
                    if (iter.hasNext() && fjp.getActiveThreadCount() < fjp.getParallelism()) {
                        step *= 2;
                        //                            System.out.println("MzXMLthreadUnit: fjp.getActiveThreadCount()\t" + fjp.getActiveThreadCount()+"\t"+step);
                    }
                }
            } catch (Exception ex) {
                Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex));
            }
        }
    }
    try {
        fileHandler.close();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    fjp.shutdown();
    try {
        fjp.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException ex) {
        throw new RuntimeException(ex);
    }
    //        for (MzXMLthreadUnit unit : ScanList) {
    //            executorPool.execute(unit);
    //        }
    //        executorPool.shutdown();
    //
    //        try {
    //            executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    //        } catch (InterruptedException e) {
    //            Logger.getRootLogger().info("interrupted..");
    //        }
    return ScanList;
}

From source file:com.netscape.cms.logging.LogFile.java

/**
 * Open the log file. This creates the buffered FileWriter
 *
 *//*from ww w . j  a  v  a  2  s  .c  om*/
protected synchronized void open() throws IOException {
    RandomAccessFile out;

    try {
        out = new RandomAccessFile(mFile, "rw");
        out.seek(out.length());
        //XXX int or long?
        mBytesWritten = (int) out.length();
        if (!Utils.isNT()) {
            try {
                Utils.exec("chmod 00640 " + mFile.getCanonicalPath());
            } catch (IOException e) {
                CMS.debug("Unable to change file permissions on " + mFile.toString());
            }
        }
        mLogWriter = new BufferedWriter(new FileWriter(out.getFD()), mBufferSize);

        // The first time we open, mSignature will not have been
        // initialized yet. That's ok, we will push our first signature
        // in setupSigning().
        if (mLogSigning && (mSignature != null)) {
            try {
                pushSignature();
            } catch (ELogException le) {
                ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_ILLEGALARGUMENT", mFileName)));
            }
        }
    } catch (IllegalArgumentException iae) {
        ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_ILLEGALARGUMENT", mFileName)));
    } catch (GeneralSecurityException gse) {
        // error with signed audit log, shutdown CMS
        ConsoleError
                .send(new SystemEvent(CMS.getUserMessage("CMS_LOG_OPEN_FAILED", mFileName, gse.toString())));
        gse.printStackTrace();
        shutdownCMS();
    }

    mBytesUnflushed = 0;
}

From source file:com.mellanox.r4h.MiniDFSCluster.java

public static boolean corruptBlock(File blockFile) throws IOException {
    if (blockFile == null || !blockFile.exists()) {
        return false;
    }//from   w  ww  . j  a  v a2s  .  c om
    // Corrupt replica by writing random bytes into replica
    Random random = new Random();
    RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
    FileChannel channel = raFile.getChannel();
    String badString = "BADBAD";
    int rand = random.nextInt((int) channel.size() / 2);
    raFile.seek(rand);
    raFile.write(badString.getBytes());
    raFile.close();
    LOG.warn("Corrupting the block " + blockFile);
    return true;
}

From source file:org.scriptbox.util.common.io.Tailer.java

/**
 * Read new lines./*from w  ww  .  jav  a 2 s .co  m*/
 *
 * @param reader The file to read
 * @return The new position after the lines have been read
 * @throws java.io.IOException if an I/O error occurs.
 */
private long readLines(RandomAccessFile reader) throws IOException {
    StringBuilder sb = new StringBuilder();

    long pos = reader.getFilePointer();
    long rePos = pos; // position to re-read

    int num;
    boolean seenCR = false;
    while (run && ((num = reader.read(inbuf)) != -1)) {
        for (int i = 0; i < num; i++) {
            byte ch = inbuf[i];
            switch (ch) {
            case '\n':
                seenCR = false; // swallow CR before LF
                listener.handle(sb.toString());
                sb.setLength(0);
                rePos = pos + i + 1;
                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);
                    rePos = pos + i + 1;
                }
                sb.append((char) ch); // add character, not its ascii value
            }
        }

        pos = reader.getFilePointer();
    }

    reader.seek(rePos); // Ensure we can re-read if necessary
    return rePos;
}

From source file:FileBaseDataMap.java

/**
 * ??value??.<br>/*from   w w w .  j av a 2 s. c  o m*/
 *
 * @param key 
 * @param hashCode This is a key value hash code
 * @return 
 * @throws
 */
public String get(String key, int hashCode) {
    byte[] tmpBytes = null;

    String ret = null;
    byte[] keyBytes = key.getBytes();
    byte[] equalKeyBytes = new byte[keyBytes.length + 1];
    byte[] lineBufs = new byte[this.getDataSize];
    boolean matchFlg = true;

    // ???
    for (int idx = 0; idx < keyBytes.length; idx++) {
        equalKeyBytes[idx] = keyBytes[idx];
    }

    equalKeyBytes[equalKeyBytes.length - 1] = 38;

    try {

        File file = dataFileList[hashCode % numberOfDataFiles];

        CacheContainer accessor = (CacheContainer) innerCache.get(file.getAbsolutePath());
        RandomAccessFile raf = null;
        BufferedWriter wr = null;

        if (accessor == null || accessor.isClosed) {

            raf = new RandomAccessFile(file, "rwd");
            wr = new BufferedWriter(new FileWriter(file, true));
            accessor = new CacheContainer();
            accessor.raf = raf;
            accessor.wr = wr;
            accessor.file = file;
            innerCache.put(file.getAbsolutePath(), accessor);
        } else {

            raf = accessor.raf;
        }

        for (int tryIdx = 0; tryIdx < 2; tryIdx++) {

            try {
                raf.seek(0);
                int readLen = -1;
                while ((readLen = raf.read(lineBufs)) != -1) {

                    matchFlg = true;

                    int loop = readLen / lineDataSize;

                    for (int loopIdx = 0; loopIdx < loop; loopIdx++) {

                        int assist = (lineDataSize * loopIdx);

                        matchFlg = true;

                        if (equalKeyBytes[equalKeyBytes.length - 1] == lineBufs[assist
                                + (equalKeyBytes.length - 1)]) {

                            for (int i = 0; i < equalKeyBytes.length; i++) {

                                if (equalKeyBytes[i] != lineBufs[assist + i]) {
                                    matchFlg = false;
                                    break;
                                }
                            }
                        } else {

                            matchFlg = false;
                        }

                        // ???????
                        if (matchFlg) {

                            tmpBytes = new byte[lineDataSize];

                            for (int i = 0; i < lineDataSize; i++) {

                                tmpBytes[i] = lineBufs[assist + i];
                            }
                            break;
                        }
                    }
                    if (matchFlg)
                        break;
                }
                break;
            } catch (IOException ie) {

                // IOException???1????
                if (tryIdx == 1)
                    throw ie;

                try {
                    if (raf != null)
                        raf.close();
                    if (wr != null)
                        wr.close();

                    raf = new RandomAccessFile(file, "rwd");
                    wr = new BufferedWriter(new FileWriter(file, true));
                    accessor = new CacheContainer();
                    accessor.raf = raf;
                    accessor.wr = wr;
                    accessor.file = file;
                    innerCache.put(file.getAbsolutePath(), accessor);
                } catch (Exception e) {
                    throw e;
                }
            }
        }

        // ?
        if (tmpBytes != null) {

            if (tmpBytes[keyDataLength] != 38) {

                int i = keyDataLength;
                int counter = 0;

                for (; i < tmpBytes.length; i++) {

                    if (tmpBytes[i] == 38)
                        break;
                    counter++;
                }

                ret = new String(tmpBytes, keyDataLength, counter, "UTF-8");
            }
        }
    } catch (Exception e) {

        e.printStackTrace();
    }

    return ret;
}

From source file:com.excuseme.rocketleaguelivestats.scanner.tailer.Tailer.java

/**
 * Read new lines.//  w w w .ja v  a  2  s .c  om
 *
 * @param reader The file to read
 * @return The new position after the lines have been read
 * @throws java.io.IOException if an I/O error occurs.
 */
private long readLines(RandomAccessFile reader) throws IOException {
    StringBuilder sb = new StringBuilder();

    long pos = reader.getFilePointer();
    long rePos = pos; // position to re-read

    int num;
    boolean seenCR = false;
    while (run && ((num = reader.read(inbuf)) != -1)) {
        for (int i = 0; i < num; i++) {
            byte ch = inbuf[i];
            switch (ch) {
            case '\n':
                seenCR = false; // swallow CR before LF
                listener.handle(sb.toString());
                sb.setLength(0);
                rePos = pos + i + 1;
                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);
                    rePos = pos + i + 1;
                }
                sb.append((char) ch); // add character, not its ascii value
            }
        }

        pos = reader.getFilePointer();
    }
    if (reader.read(inbuf) == -1) {
        listener.endOfFile();
    }

    reader.seek(rePos); // Ensure we can re-read if necessary
    return rePos;
}