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:com.polyvi.xface.extension.advancedfiletransfer.FileUploader.java

/**
 * ?buffer?,??/* w  w w. ja  v  a2 s .co  m*/
 *
 * @param buffer
 *            :??
 */
private int readFileData(byte[] buffer) {
    int len = READ_FILE_END;
    RandomAccessFile accessFile = null;
    try {
        accessFile = new RandomAccessFile(mUploadFile, "r");
        accessFile.seek(mStartedPosition);
        len = accessFile.read(buffer);
        if (mStartedPosition != mAlreadyUploadLength) {
            mAlreadyUploadLength = mStartedPosition;
        }
        accessFile.close();
    } catch (FileNotFoundException e) {
        len = READ_FILE_END;
        onError(FILE_NOT_FOUND_ERR);
    } catch (IOException e) {
        len = READ_FILE_END;
        onError(FILE_NOT_FOUND_ERR);
    }
    return len;
}

From source file:com.csipsimple.service.DownloadLibService.java

private void dumpFile(HttpEntity entity, File partialDestinationFile, File destinationFile) throws IOException {
    if (!cancellingDownload) {
        totalSize = (int) entity.getContentLength();
        if (totalSize <= 0) {
            totalSize = 1024;/*from w w  w  .j av a 2s  .  c  o m*/
        }

        byte[] buff = new byte[64 * 1024];
        int read = 0;
        RandomAccessFile out = new RandomAccessFile(partialDestinationFile, "rw");
        out.seek(0);
        InputStream is = entity.getContent();
        TimerTask progressUpdateTimerTask = new TimerTask() {
            @Override
            public void run() {
                onProgressUpdate();
            }
        };
        Timer progressUpdateTimer = new Timer();
        try {
            // If File exists, set the Progress to it. Otherwise it will be
            // initial 0
            downloadedSize = 0;
            progressUpdateTimer.scheduleAtFixedRate(progressUpdateTimerTask, 100, 100);
            while ((read = is.read(buff)) > 0 && !cancellingDownload) {
                out.write(buff, 0, read);
                downloadedSize += read;
            }
            out.close();
            is.close();
            if (!cancellingDownload) {
                partialDestinationFile.renameTo(destinationFile);
            }
        } catch (IOException e) {
            out.close();
            try {
                destinationFile.delete();
            } catch (SecurityException ex) {
                Log.e(THIS_FILE, "Unable to delete downloaded File. Continue anyway.", ex);
            }
        } finally {
            progressUpdateTimer.cancel();
            buff = null;
        }
    }
}

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);
    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();/* w w w .j a  va2 s  .  c  om*/
    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:org.commoncrawl.service.listcrawler.HDFSFileIndex.java

private HDFSFileIndex.IndexDataBlock demandLoadIndexDataBlock(long fingerprint, int itemDataOffset,
        int itemDataSize) throws IOException {
    // ok time to load this block ...
    RandomAccessFile file = new RandomAccessFile(_localIndexFilePath, "r");

    try {//  ww  w  .ja v  a 2  s .co  m

        ByteBuffer bufferOut = ByteBuffer.allocate(itemDataSize);

        if (bufferOut != null) {
            file.seek(_indexDataOffset + itemDataOffset);
            file.readFully(bufferOut.array());
            HDFSFileIndex.IndexDataBlock dataBlock = new IndexDataBlock(fingerprint, 0, bufferOut);
            return dataBlock;
        } else {
            throw new IOException("Unable to allocate byte buffer!!!");
        }
    } finally {
        if (file != null) {
            file.close();
        }
    }
}

From source file:raptor.service.DictionaryService.java

public String[] getWordsThatStartWith(String string) {
    List<String> result = new ArrayList<String>(10);

    string = string.toLowerCase();// w w  w  .j  a  v  a2s  .c  om
    long startTime = System.currentTimeMillis();
    RandomAccessFile raf = null;
    try {
        File file = new File(DICTIONARY_PATH);
        raf = new RandomAccessFile(file, "r");

        long low = 0;
        long high = file.length();

        long p = -1;
        while (low < high) {
            long mid = (low + high) / 2;
            p = mid;
            while (p >= 0) {
                raf.seek(p);

                char c = (char) raf.readByte();
                if (c == '\n')
                    break;
                p--;
            }
            if (p < 0)
                raf.seek(0);
            String line = raf.readLine();
            // Useful for debugging
            // System.out.println("-- " + mid + " " + line);
            if (line == null) {
                low = high;
            } else {
                int compare = line.compareTo(string);
                if (compare < 0) {
                    low = mid + 1;
                } else if (compare == 0) {
                    low = p;
                    break;
                } else {
                    high = mid;
                }
            }
        }

        p = low;
        while (p >= 0 && p < high) {
            raf.seek(p);
            if (((char) raf.readByte()) == '\n')
                break;
            p--;
        }

        if (p < 0)
            raf.seek(0);

        String line = raf.readLine();
        while (line != null && line.startsWith(string)) {
            result.add(line);
            line = raf.readLine();
        }
    } catch (Throwable t) {
        Raptor.getInstance().onError("Error reading dictionary file: " + DICTIONARY_PATH, t);
    } finally {
        try {
            raf.close();
        } catch (Throwable t) {
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Searched " + string + " (" + (System.currentTimeMillis() - startTime) + ") " + result);
        }

    }
    return result.toArray(new String[0]);
}

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

@Test
public void testNext() throws IOException {
    RandomAccessFile r = new RandomAccessFile(testMeta.testFile, "r");
    r.seek(0);
    Assert.assertNull(storage.retrieve(new byte[8]));
    byte[] b = r.readLine().getBytes();
    storage.store(new Slice(b, 0, b.length));
    byte[] b1 = r.readLine().getBytes();
    storage.store(new Slice(b1, 0, b1.length));
    storage.store(new Slice(b, 0, b.length));
    storage.flush();//from www.  j a va2s. co  m
    storage.store(new Slice(b1, 0, b1.length));
    storage.store(new Slice(b, 0, b.length));
    storage.flush();
    byte[] data = storage.retrieve(new byte[8]);
    byte[] tempData = new byte[data.length - 8];
    System.arraycopy(data, 8, tempData, 0, tempData.length);
    Assert.assertEquals("matched the stored value with retrieved value", new String(b), new String(tempData));
    data = storage.retrieveNext();
    tempData = new byte[data.length - 8];
    System.arraycopy(data, 8, tempData, 0, tempData.length);
    Assert.assertEquals("matched the stored value with retrieved value", new String(b1), new String(tempData));
    data = storage.retrieveNext();
    tempData = new byte[data.length - 8];
    System.arraycopy(data, 8, tempData, 0, tempData.length);
    Assert.assertEquals("matched the stored value with retrieved value", new String(b), new String(tempData));
    r.close();
}

From source file:net.gleamynode.oil.impl.wal.store.FileLogStore.java

public void open() {
    if (isOpen()) {
        throw new IllegalStateException();
    }/*from  ww  w .j  a  va2 s .c  o m*/

    parseProperties();

    try {
        File parentDir = file.getCanonicalFile().getParentFile();

        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }
    } catch (IOException e) {
        throw new OilException("failed to get parent directory path.", e);
    }

    RandomAccessFile raf = null;

    if (!useExternalCatalog) {
        catalog = new ClassCatalog(file.getPath() + ".cat");
    }

    boolean done = false;

    try {
        raf = new RandomAccessFile(file, "rw");
        raf.seek(0L);
        reader = new FileLogReader(catalog, raf, new FileInputStream(raf.getFD()), maxItemSize);
        raf = new RandomAccessFile(file, "rw");
        raf.seek(raf.length());
        writer = new FileLogWriter(catalog, new FileOutputStream(raf.getFD()), maxItemSize);

        flusher = new Flusher();
        flusher.start();
        done = true;
    } catch (IOException e) {
        throw new OilException(e);
    } finally {
        if (!done) {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }

                reader = null;
            }

            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                }

                writer = null;
            }

            if (!useExternalCatalog) {
                catalog.close();
            }
        }
    }
}

From source file:com.haulmont.cuba.core.sys.LogControlImpl.java

protected String readUtf8Line(RandomAccessFile logFile) throws IOException {
    int c = -1;/* ww w.j ava2 s  . co  m*/
    boolean eol = false;
    ByteArrayOutputStream input = new ByteArrayOutputStream();

    while (!eol) {
        switch (c = logFile.read()) {
        case -1:
        case '\n':
            eol = true;
            break;
        case '\r':
            eol = true;
            long cur = logFile.getFilePointer();
            if ((logFile.read()) != '\n') {
                logFile.seek(cur);
            }
            break;
        default:
            input.write((byte) c);
            break;
        }
    }
    if ((c == -1) && (input.size() == 0)) {
        return null;
    }

    return new String(input.toByteArray(), StandardCharsets.UTF_8);
}

From source file:cc.arduino.utils.network.FileDownloader.java

private void downloadFile(boolean noResume) throws InterruptedException {
    RandomAccessFile file = null;

    try {//  ww  w . jav a2  s.  co  m
        // Open file and seek to the end of it
        file = new RandomAccessFile(outputFile, "rw");
        initialSize = file.length();

        if (noResume && initialSize > 0) {
            // delete file and restart downloading
            Files.delete(outputFile.toPath());
            initialSize = 0;
        }

        file.seek(initialSize);

        setStatus(Status.CONNECTING);

        Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(downloadUrl.toURI());
        if ("true".equals(System.getProperty("DEBUG"))) {
            System.err.println("Using proxy " + proxy);
        }

        HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(proxy);
        connection.setRequestProperty("User-agent", userAgent);
        if (downloadUrl.getUserInfo() != null) {
            String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
            connection.setRequestProperty("Authorization", auth);
        }

        connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
        connection.setConnectTimeout(5000);
        setDownloaded(0);

        // Connect
        connection.connect();
        int resp = connection.getResponseCode();

        if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) {
            URL newUrl = new URL(connection.getHeaderField("Location"));

            proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(newUrl.toURI());

            // open the new connnection again
            connection = (HttpURLConnection) newUrl.openConnection(proxy);
            connection.setRequestProperty("User-agent", userAgent);
            if (downloadUrl.getUserInfo() != null) {
                String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
                connection.setRequestProperty("Authorization", auth);
            }

            connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
            connection.setConnectTimeout(5000);

            connection.connect();
            resp = connection.getResponseCode();
        }

        if (resp < 200 || resp >= 300) {
            throw new IOException("Received invalid http status code from server: " + resp);
        }

        // Check for valid content length.
        long len = connection.getContentLength();
        if (len >= 0) {
            setDownloadSize(len);
        }
        setStatus(Status.DOWNLOADING);

        synchronized (this) {
            stream = connection.getInputStream();
        }
        byte buffer[] = new byte[10240];
        while (status == Status.DOWNLOADING) {
            int read = stream.read(buffer);
            if (read == -1)
                break;

            file.write(buffer, 0, read);
            setDownloaded(getDownloaded() + read);

            if (Thread.interrupted()) {
                file.close();
                throw new InterruptedException();
            }
        }

        if (getDownloadSize() != null) {
            if (getDownloaded() < getDownloadSize())
                throw new Exception("Incomplete download");
        }
        setStatus(Status.COMPLETE);
    } catch (InterruptedException e) {
        setStatus(Status.CANCELLED);
        // lets InterruptedException go up to the caller
        throw e;

    } catch (SocketTimeoutException e) {
        setStatus(Status.CONNECTION_TIMEOUT_ERROR);
        setError(e);

    } catch (Exception e) {
        setStatus(Status.ERROR);
        setError(e);

    } finally {
        IOUtils.closeQuietly(file);

        synchronized (this) {
            IOUtils.closeQuietly(stream);
        }
    }
}

From source file:org.artifactory.webapp.wicket.page.logs.SystemLogsViewPanel.java

/**
 * Attemps to continue reading the log file from the last position, and the updates the log path, size and link
 * According to the outcome.//from w  w  w. j  a v  a  2  s. c om
 *
 * @param cleanPanel True if the text container should be cleaned of content. false if not
 * @return String - The newly read content
 */
protected String readLogAndUpdateSize(boolean cleanPanel) {
    if ((lastPointer > systemLogFile.length()) || cleanPanel) {
        lastPointer = 0;
    }
    long size = systemLogFile.length();
    setLogInfo();
    if (lastPointer == size) {
        return "";
    }
    StringBuilder sb = new StringBuilder();
    RandomAccessFile logRandomAccessFile = null;
    try {
        logRandomAccessFile = new RandomAccessFile(systemLogFile, "r");

        //If the log file is larger than 100K
        if (lastPointer == 0 && logRandomAccessFile.length() > FIRST_READ_BLOCK_SIZE) {
            //Point to the begining of the last 100K
            lastPointer = logRandomAccessFile.length() - FIRST_READ_BLOCK_SIZE;
        }
        logRandomAccessFile.seek(lastPointer);

        String line;
        while ((line = logRandomAccessFile.readLine()) != null) {
            CharSequence escapedLine = Strings.escapeMarkup(line, false, false);
            sb.append("<div>").append(escapedLine).append("<br/></div>");
        }
        lastPointer = logRandomAccessFile.getFilePointer();

    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    } finally {
        try {
            if (logRandomAccessFile != null) {
                logRandomAccessFile.close();
            }
        } catch (IOException ignore) {
        }
    }
    return sb.toString();
}