Example usage for java.io RandomAccessFile setLength

List of usage examples for java.io RandomAccessFile setLength

Introduction

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

Prototype

public native void setLength(long newLength) throws IOException;

Source Link

Document

Sets the length of this file.

Usage

From source file:org.myframe.http.FileRequest.java

public byte[] handleResponse(HttpResponse response) throws IOException, KJHttpException {
    HttpEntity entity = response.getEntity();
    long fileSize = entity.getContentLength();
    if (fileSize <= 0) {
        MLoger.debug("Response doesn't present Content-Length!");
    }/*from  w ww  . ja va  2 s  . co m*/

    long downloadedSize = mTemporaryFile.length();
    boolean isSupportRange = HttpUtils.isSupportRange(response);
    if (isSupportRange) {
        fileSize += downloadedSize;

        String realRangeValue = HttpUtils.getHeader(response, "Content-Range");
        if (!TextUtils.isEmpty(realRangeValue)) {
            String assumeRangeValue = "bytes " + downloadedSize + "-" + (fileSize - 1);
            if (TextUtils.indexOf(realRangeValue, assumeRangeValue) == -1) {
                throw new IllegalStateException("The Content-Range Header is invalid Assume[" + assumeRangeValue
                        + "] vs Real[" + realRangeValue + "], " + "please remove the temporary file ["
                        + mTemporaryFile + "].");
            }
        }
    }

    if (fileSize > 0 && mStoreFile.length() == fileSize) {
        mStoreFile.renameTo(mTemporaryFile);
        mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, fileSize);
        return null;
    }

    RandomAccessFile tmpFileRaf = new RandomAccessFile(mTemporaryFile, "rw");
    if (isSupportRange) {
        tmpFileRaf.seek(downloadedSize);
    } else {
        tmpFileRaf.setLength(0);
        downloadedSize = 0;
    }

    try {
        InputStream in = entity.getContent();
        if (HttpUtils.isGzipContent(response) && !(in instanceof GZIPInputStream)) {
            in = new GZIPInputStream(in);
        }
        byte[] buffer = new byte[6 * 1024]; // 6K buffer
        int offset;

        while ((offset = in.read(buffer)) != -1) {
            tmpFileRaf.write(buffer, 0, offset);

            downloadedSize += offset;
            mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, downloadedSize);

            if (isCanceled()) {
                break;
            }
        }
    } finally {
        try {
            if (entity != null)
                entity.consumeContent();
        } catch (Exception e) {
            MLoger.debug("Error occured when calling consumingContent");
        }
        tmpFileRaf.close();
    }
    return null;
}

From source file:com.scut.easyfe.network.kjFrame.http.FileRequest.java

public byte[] handleResponse(HttpResponse response) throws IOException, KJHttpException {
    HttpEntity entity = response.getEntity();
    long fileSize = entity.getContentLength();
    if (fileSize <= 0) {
        KJLoger.debug("Response doesn't present Content-Length!");
    }/*from ww w .  j a va  2  s  .  c om*/

    long downloadedSize = mTemporaryFile.length();
    boolean isSupportRange = HttpUtils.isSupportRange(response);
    if (isSupportRange) {
        fileSize += downloadedSize;

        String realRangeValue = HttpUtils.getHeader(response, "Content-Range");
        if (!TextUtils.isEmpty(realRangeValue)) {
            String assumeRangeValue = "bytes " + downloadedSize + "-" + (fileSize - 1);
            if (TextUtils.indexOf(realRangeValue, assumeRangeValue) == -1) {
                throw new IllegalStateException("The Content-Range Header is invalid Assume[" + assumeRangeValue
                        + "] vs Real[" + realRangeValue + "], " + "please remove the temporary file ["
                        + mTemporaryFile + "].");
            }
        }
    }

    if (fileSize > 0 && mStoreFile.length() == fileSize) {
        mStoreFile.renameTo(mTemporaryFile);
        mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, fileSize);
        return null;
    }

    RandomAccessFile tmpFileRaf = new RandomAccessFile(mTemporaryFile, "rw");
    if (isSupportRange) {
        tmpFileRaf.seek(downloadedSize);
    } else {
        tmpFileRaf.setLength(0);
        downloadedSize = 0;
    }

    try {
        InputStream in = entity.getContent();
        if (HttpUtils.isGzipContent(response) && !(in instanceof GZIPInputStream)) {
            in = new GZIPInputStream(in);
        }
        byte[] buffer = new byte[6 * 1024]; // 6K buffer
        int offset;

        while ((offset = in.read(buffer)) != -1) {
            tmpFileRaf.write(buffer, 0, offset);

            downloadedSize += offset;
            mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, downloadedSize);

            if (isCanceled()) {
                break;
            }
        }
    } finally {
        try {
            if (entity != null)
                entity.consumeContent();
        } catch (Exception e) {
            KJLoger.debug("Error occured when calling consumingContent");
        }
        tmpFileRaf.close();
    }
    return null;
}

From source file:com.btoddb.fastpersitentqueue.JournalFileTest.java

@Test
public void testInvalidUUID() throws Exception {
    // can't actuall write an invalid UUID because it's made of two variable length longs
    // only way to get an invalid UUID is to have a truncated file
    JournalFile jf1 = new JournalFile(theFile);
    jf1.initForWriting(new UUID());
    jf1.close();/*from w w  w .  j a  va 2  s .  c  om*/

    // mess up the UUID
    RandomAccessFile raFile = new RandomAccessFile(theFile, "rw");
    Utils.writeInt(raFile, 1);
    Utils.writeInt(raFile, -1);
    raFile.setLength(raFile.getFilePointer());
    raFile.close();
    //        Utils.writeLong(raFile, numberOfEntries.get());

    JournalFile jf2 = new JournalFile(theFile);
    try {
        jf2.initForReading();
        fail("should have found invalid UUID in the form of truncated file");
    } catch (EOFException e) {
        // good!
    }
}

From source file:org.waveprotocol.box.server.persistence.file.DeltaStoreTest.java

public void testRecoverFromTruncatedDeltas() throws Exception {
    // Create an entry with one record. Shrink the file byte by byte and ensure
    // we can read it without crashing.
    DeltaStore store = newDeltaStore();/*from ww w.  jav a  2 s.  c  o m*/
    WaveletDeltaRecord written = createRecord();
    File deltaFile = FileDeltaCollection.deltasFile(path.getAbsolutePath(), WAVE1_WAVELET1);

    long toRemove = 1;
    while (true) {
        // This generates the full file.
        DeltasAccess wavelet = store.open(WAVE1_WAVELET1);
        wavelet.append(ImmutableList.of(written));
        wavelet.close();

        RandomAccessFile file = new RandomAccessFile(deltaFile, "rw");
        if (toRemove > file.length()) {
            file.close();
            break;
        }
        // eat the planned number of bytes
        LOG.info("trying to remove " + toRemove + " bytes");
        file.setLength(file.length() - toRemove);
        file.close();

        wavelet = store.open(WAVE1_WAVELET1);
        WaveletDeltaRecord read = wavelet.getDelta(0);
        assertNull("got an unexpected record " + read, read);
        wavelet.close();
        toRemove++;
    }
}

From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java

private void updateData(byte[] text, String javaHome, String end, RandomAccessFile file) throws IOException {
    String data = new String(text);
    data = StringUtils.replace(data, end, javaHome);
    file.setLength(data.length());
    file.writeBytes(data);/*  w ww  .j av a2  s  . c om*/
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestFSEditLogLoader.java

/**
 * Truncate the given file to the given length
 *///from   www .  j a va  2s  . com
private void truncateFile(File logFile, long newLength) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(logFile, "rw");
    raf.setLength(newLength);
    raf.close();
}

From source file:com.adaptris.core.fs.NonDeletingFsConsumerTest.java

private void resize(List<File> files) throws IOException {
    for (File f : files) {
        long currentSize = f.length();
        RandomAccessFile raf = new RandomAccessFile(f, "rwd");
        try {/*from  ww  w. j  a  v a 2 s  . c  o  m*/
            raf.setLength(currentSize + 1);
        } finally {
            raf.close();
        }
    }
}

From source file:org.apache.hcatalog.pig.TestHCatLoader.java

@Test
public void testGetInputBytes() throws Exception {
    File file = new File(TEST_WAREHOUSE_DIR + "/" + SPECIFIC_SIZE_TABLE + "/part-m-00000");
    file.deleteOnExit();//from  w ww.  j  a va  2 s.  c  o  m
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
    randomAccessFile.setLength(2L * 1024 * 1024 * 1024);
    randomAccessFile.close();
    Job job = new Job();
    HCatLoader hCatLoader = new HCatLoader();
    hCatLoader.setUDFContextSignature("testGetInputBytes");
    hCatLoader.setLocation(SPECIFIC_SIZE_TABLE, job);
    ResourceStatistics statistics = hCatLoader.getStatistics(file.getAbsolutePath(), job);
    assertEquals(2048, (long) statistics.getmBytes());
}

From source file:com.example.android.vault.EncryptedDocument.java

/**
 * Encrypt and write both the metadata and content sections of this
 * document, reading the content from the given pipe. Internally uses
 * {@link ParcelFileDescriptor#checkError()} to verify that content arrives
 * without errors. Writes to temporary file to keep atomic view of contents,
 * swapping into place only when write is successful.
 * <p/>// w ww .  ja  va2 s  .  c om
 * Pipe is left open, so caller is responsible for calling
 * {@link ParcelFileDescriptor#close()} or
 * {@link ParcelFileDescriptor#closeWithError(String)}.
 *
 * @param contentIn read end of a pipe.
 */
public void writeMetadataAndContent(JSONObject meta, ParcelFileDescriptor contentIn)
        throws IOException, GeneralSecurityException {
    // Write into temporary file to provide an atomic view of existing
    // contents during write, and also to recover from failed writes.
    final String tempName = mFile.getName() + ".tmp_" + Thread.currentThread().getId();
    final File tempFile = new File(mFile.getParentFile(), tempName);

    RandomAccessFile f = new RandomAccessFile(tempFile, "rw");
    try {
        // Truncate any existing data
        f.setLength(0);

        // Write content first to detect size
        if (contentIn != null) {
            f.seek(CONTENT_OFFSET);
            final int plainLength = writeSection(f, new FileInputStream(contentIn.getFileDescriptor()));
            meta.put(Document.COLUMN_SIZE, plainLength);

            // Verify that remote side of pipe finished okay; if they
            // crashed or indicated an error then this throws and we
            // leave the original file intact and clean up temp below.
            contentIn.checkError();
        }

        meta.put(Document.COLUMN_DOCUMENT_ID, mDocId);
        meta.put(Document.COLUMN_LAST_MODIFIED, System.currentTimeMillis());

        // Rewind and write metadata section
        f.seek(0);
        f.writeInt(MAGIC_NUMBER);

        final ByteArrayInputStream metaIn = new ByteArrayInputStream(
                meta.toString().getBytes(StandardCharsets.UTF_8));
        writeSection(f, metaIn);

        if (f.getFilePointer() > CONTENT_OFFSET) {
            throw new IOException("Metadata section was too large");
        }

        // Everything written fine, atomically swap new data into place.
        // fsync() before close would be overkill, since rename() is an
        // atomic barrier.
        f.close();
        tempFile.renameTo(mFile);

    } catch (JSONException e) {
        throw new IOException(e);
    } finally {
        // Regardless of what happens, always try cleaning up.
        f.close();
        tempFile.delete();
    }
}

From source file:jp.andeb.obbutil.ObbUtilMain.java

private static boolean doAdd(String[] args) {
    final CommandLine commandLine;
    try {/*from  w  w w.ja v  a2  s  . c  o  m*/
        final CommandLineParser parser = new GnuParser();
        commandLine = parser.parse(OPTIONS_FOR_ADD, args);
    } catch (MissingArgumentException e) {
        System.err.println("??????: " + e.getOption().getOpt());
        printUsage(PROGNAME);
        return false;
    } catch (MissingOptionException e) {
        System.err.println("??????: " + e.getMissingOptions());
        printUsage(PROGNAME);
        return false;
    } catch (UnrecognizedOptionException e) {
        System.err.println("????: " + e.getOption());
        printUsage(PROGNAME);
        return false;
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        printUsage(PROGNAME);
        return false;
    }

    final String pkgName = commandLine.getOptionValue(PACKAGE_NAME.getOpt());
    final String versionStr = commandLine.getOptionValue(OBB_VERSION.getOpt());
    final Integer version = toInteger(versionStr);
    if (version == null) {
        System.err.println("??????: " + versionStr);
        printUsage(PROGNAME);
        return false;
    }
    final boolean isOverlay = commandLine.hasOption(OVERLAY_FLAG.getOpt());
    final String saltStr = commandLine.getOptionValue(SALT.getOpt());
    final byte[] salt;
    if (saltStr == null) {
        salt = null;
    } else {
        salt = toByteArray(saltStr, ObbInfoV1.SALT_LENGTH);
        if (salt == null) {
            System.err.println("????: " + saltStr);
            printUsage(PROGNAME);
            return false;
        }
    }

    final String[] nonRecognizedArgs = commandLine.getArgs();
    if (nonRecognizedArgs.length == 0) {
        System.err.println("????????");
        printUsage(PROGNAME);
        return false;
    }
    if (nonRecognizedArgs.length != 1) {
        System.err.println("???????");
        printUsage(PROGNAME);
        return false;
    }

    final File targetFile = new File(nonRecognizedArgs[0]);
    final RandomAccessFile targetRaFile;
    try {
        targetRaFile = new RandomAccessFile(targetFile, "rw");
    } catch (FileNotFoundException e) {
        System.err.println("????: " + targetFile.getPath());
        return false;
    }
    try {
        try {
            final ObbInfoV1 info = ObbInfoV1.fromFile(targetRaFile);
            System.err.println(
                    "?? OBB ???????: " + info.toString());
            return false;
        } catch (IOException e) {
            System.err
                    .println("????????: " + targetFile.getPath());
            return false;
        } catch (NotObbException e) {
            // 
        }

        int flag = 0;
        if (isOverlay) {
            flag |= ObbInfoV1.FLAG_OVERLAY;
        }
        if (salt != null) {
            flag |= ObbInfoV1.FLAG_SALTED;
        }
        final ObbInfoV1 obbInfo = new ObbInfoV1(flag, salt, pkgName, version.intValue());
        final ByteBuffer obbInfoBytes = obbInfo.toBytes();
        // ???
        targetRaFile.setLength(targetRaFile.length() + obbInfoBytes.remaining());
        targetRaFile.seek(targetRaFile.length() - obbInfoBytes.remaining());
        targetRaFile.write(obbInfoBytes.array(), obbInfoBytes.arrayOffset(), obbInfoBytes.remaining());
    } catch (IOException e) {
        System.err.println("OBB ?????????: " + targetFile.getPath());
        return false;
    } finally {
        try {
            targetRaFile.close();
        } catch (IOException e) {
            System.err.println("OBB ?????????: " + targetFile.getPath());
            return false;
        }
    }
    System.err.println("OBB ??????????: " + targetFile.getPath());
    return true;
}