Example usage for java.io RandomAccessFile write

List of usage examples for java.io RandomAccessFile write

Introduction

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

Prototype

public void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this file.

Usage

From source file:com.amazonaws.services.glacier.transfer.ArchiveTransferManager.java

/**
 * Writes the data from the given input stream to the given output stream.
 *//*w w  w.j a v  a2  s .  com*/
private void appendToFile(RandomAccessFile output, InputStream input) throws IOException {
    byte[] buffer = new byte[1024 * 1024];
    int bytesRead = 0;
    do {
        bytesRead = input.read(buffer);
        if (bytesRead < 0)
            break;
        output.write(buffer, 0, bytesRead);
    } while (bytesRead > 0);
    return;
}

From source file:com.cloud.storage.template.HttpTemplateDownloader.java

@Override
public long download(boolean resume, DownloadCompleteCallback callback) {
    switch (status) {
    case ABORTED:
    case UNRECOVERABLE_ERROR:
    case DOWNLOAD_FINISHED:
        return 0;
    default:/*from w w w.j av a 2 s.c o m*/

    }
    int bytes = 0;
    File file = new File(toFile);
    try {

        long localFileSize = 0;
        if (file.exists() && resume) {
            localFileSize = file.length();
            s_logger.info("Resuming download to file (current size)=" + localFileSize);
        }

        Date start = new Date();

        int responseCode = 0;

        if (localFileSize > 0) {
            // require partial content support for resume
            request.addRequestHeader("Range", "bytes=" + localFileSize + "-");
            if (client.executeMethod(request) != HttpStatus.SC_PARTIAL_CONTENT) {
                errorString = "HTTP Server does not support partial get";
                status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
                return 0;
            }
        } else if ((responseCode = client.executeMethod(request)) != HttpStatus.SC_OK) {
            status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
            errorString = " HTTP Server returned " + responseCode + " (expected 200 OK) ";
            return 0; //FIXME: retry?
        }

        Header contentLengthHeader = request.getResponseHeader("Content-Length");
        boolean chunked = false;
        long remoteSize2 = 0;
        if (contentLengthHeader == null) {
            Header chunkedHeader = request.getResponseHeader("Transfer-Encoding");
            if (chunkedHeader == null || !"chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
                status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
                errorString = " Failed to receive length of download ";
                return 0; //FIXME: what status do we put here? Do we retry?
            } else if ("chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
                chunked = true;
            }
        } else {
            remoteSize2 = Long.parseLong(contentLengthHeader.getValue());
        }

        if (remoteSize == 0) {
            remoteSize = remoteSize2;
        }

        if (remoteSize > MAX_TEMPLATE_SIZE_IN_BYTES) {
            s_logger.info("Remote size is too large: " + remoteSize + " , max=" + MAX_TEMPLATE_SIZE_IN_BYTES);
            status = Status.UNRECOVERABLE_ERROR;
            errorString = "Download file size is too large";
            return 0;
        }

        if (remoteSize == 0) {
            remoteSize = MAX_TEMPLATE_SIZE_IN_BYTES;
        }

        InputStream in = !chunked ? new BufferedInputStream(request.getResponseBodyAsStream())
                : new ChunkedInputStream(request.getResponseBodyAsStream());

        RandomAccessFile out = new RandomAccessFile(file, "rwd");
        out.seek(localFileSize);

        s_logger.info("Starting download from " + getDownloadUrl() + " to " + toFile + " remoteSize="
                + remoteSize + " , max size=" + MAX_TEMPLATE_SIZE_IN_BYTES);

        byte[] block = new byte[CHUNK_SIZE];
        long offset = 0;
        boolean done = false;
        status = TemplateDownloader.Status.IN_PROGRESS;
        while (!done && status != Status.ABORTED && offset <= remoteSize) {
            if ((bytes = in.read(block, 0, CHUNK_SIZE)) > -1) {
                out.write(block, 0, bytes);
                offset += bytes;
                out.seek(offset);
                totalBytes += bytes;
            } else {
                done = true;
            }
        }
        Date finish = new Date();
        String downloaded = "(incomplete download)";
        if (totalBytes >= remoteSize) {
            status = TemplateDownloader.Status.DOWNLOAD_FINISHED;
            downloaded = "(download complete remote=" + remoteSize + "bytes)";
        }
        errorString = "Downloaded " + totalBytes + " bytes " + downloaded;
        downloadTime += finish.getTime() - start.getTime();
        out.close();

        return totalBytes;
    } catch (HttpException hte) {
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
        errorString = hte.getMessage();
    } catch (IOException ioe) {
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR; //probably a file write error?
        errorString = ioe.getMessage();
    } finally {
        if (status == Status.UNRECOVERABLE_ERROR && file.exists() && !file.isDirectory()) {
            file.delete();
        }
        request.releaseConnection();
        if (callback != null) {
            callback.downloadComplete(status);
        }
    }
    return 0;
}

From source file:com.vincestyling.netroid.request.FileDownloadRequest.java

/**
 * In this method, we got the Content-Length, with the TemporaryFile length,
 * we can calculate the actually size of the whole file, if TemporaryFile not exists,
 * we'll take the store file length then compare to actually size, and if equals,
 * we consider this download was already done.
 * We used {@link RandomAccessFile} to continue download, when download success,
 * the TemporaryFile will be rename to StoreFile.
 *///  w  ww .j a va  2  s .com
@Override
public byte[] handleResponse(HttpResponse response, Delivery delivery) throws IOException, ServerError {
    // Content-Length might be negative when use HttpURLConnection because it default header Accept-Encoding is gzip,
    // we can force set the Accept-Encoding as identity in prepare() method to slove this problem but also disable gzip response.
    HttpEntity entity = response.getEntity();
    long fileSize = entity.getContentLength();
    if (fileSize <= 0) {
        NetroidLog.d("Response doesn't present Content-Length!");
    }

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

        // Verify the Content-Range Header, to ensure temporary file is part of the whole file.
        // Sometime, temporary file length add response content-length might greater than actual file length,
        // in this situation, we consider the temporary file is invalid, then throw an exception.
        String realRangeValue = HttpUtils.getHeader(response, "Content-Range");
        // response Content-Range may be null when "Range=bytes=0-"
        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 + "].");
            }
        }
    }

    // Compare the store file size(after download successes have) to server-side Content-Length.
    // temporary file will rename to store file after download success, so we compare the
    // Content-Length to ensure this request already download or not.
    if (fileSize > 0 && mStoreFile.length() == fileSize) {
        // Rename the store file to temporary file, mock the download success. ^_^
        mStoreFile.renameTo(mTemporaryFile);

        // Deliver download progress.
        delivery.postDownloadProgress(this, fileSize, fileSize);

        return null;
    }

    RandomAccessFile tmpFileRaf = new RandomAccessFile(mTemporaryFile, "rw");

    // If server-side support range download, we seek to last point of the temporary file.
    if (isSupportRange) {
        tmpFileRaf.seek(downloadedSize);
    } else {
        // If not, truncate the temporary file then start download from beginning.
        tmpFileRaf.setLength(0);
        downloadedSize = 0;
    }

    InputStream in = null;
    try {
        in = entity.getContent();
        // Determine the response gzip encoding, support for HttpClientStack download.
        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;
            delivery.postDownloadProgress(this, fileSize, downloadedSize);

            if (isCanceled()) {
                delivery.postCancel(this);
                break;
            }
        }
    } finally {
        try {
            // Close the InputStream
            if (in != null)
                in.close();
        } catch (Exception e) {
            NetroidLog.v("Error occured when calling InputStream.close");
        }

        try {
            // release the resources by "consuming the content".
            entity.consumeContent();
        } catch (Exception e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            NetroidLog.v("Error occured when calling consumingContent");
        }
        tmpFileRaf.close();
    }

    return null;
}

From source file:com.funambol.foundation.util.FileSystemDAOHelper.java

/**
 * Writes the InputStream in append to the file starting from the given
 * position. If the file size does not match the expected value an
 * EOFException is thrown./*  www . j a  v  a2s .com*/
 *
 * @param f the file to open in writing
 * @param in the InputStream to copy in the file
 * @param pos the file-pointer offset
 * @param expectedSize the expected file size
 * @throws IOException if an error occurs
 */
public void copyInRandomAccessFile(File f, InputStream in, long pos, long expectedSize) throws IOException {

    //
    // open file for reading and writing: also its metadata will be updated
    //
    RandomAccessFile raf = new RandomAccessFile(f, "rws");

    raf.seek(pos);
    byte[] buffer = new byte[1024];
    long count = 0;
    while (true) {
        int read = in.read(buffer);
        if (read < 0) {
            break;
        }
        count += read;
        if (expectedSize >= 0 && count > expectedSize) {
            throw new EOFException("More bytes (" + count + ") than expected (" + expectedSize + ")");
        }
        raf.write(buffer, 0, read);
    }
    raf.close();

    if (expectedSize >= 0 && count < expectedSize) {
        throw new EOFException("Less bytes (" + count + ") than expected (" + expectedSize + ")");
    }
}

From source file:com.louding.frame.http.download.FileEntityHandler.java

public File handleEntity(HttpEntity entity, DownloadProgress callback, File save, boolean isResume)
        throws IOException {
    long current = 0;
    RandomAccessFile file = new RandomAccessFile(save, "rw");
    if (isResume) {
        current = file.length();/*from   w w  w  . j  ava 2 s  .co m*/
    }
    InputStream input = entity.getContent();
    long count = entity.getContentLength() + current;
    if (mStop) {
        FileUtils.closeIO(file);
        return save;
    }
    // ???????
    /**
     *  <br>
     * current = input.skip(current); <br>
     * file.seek(current); <br>
     * ?JDKInputstream.skip(long i)i<br>
     * ? n ???????
     */
    file.seek(input.skip(current));

    int readLen = 0;
    byte[] buffer = new byte[1024];

    while ((readLen = input.read(buffer, 0, 1024)) != -1) {
        if (mStop) {
            break;
        } else {
            file.write(buffer, 0, readLen);
            current += readLen;
            callback.onProgress(count, current);
        }
    }
    callback.onProgress(count, current);

    if (mStop && current < count) { // ?
        FileUtils.closeIO(file);
        throw new IOException("user stop download thread");
    }
    FileUtils.closeIO(file);
    return save;
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java

public boolean resumeImages(String msgSubject) {
    File file = null;//from  w  w  w. ja v a 2  s.  c om
    long fileLength;

    try {

        String filename = "", num = "";

        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();

        num = getNumber(msgSubject);
        filename = getTimestamp(msgSubject);

        file = new File(fileDir + "/" + getNumber(msgSubject) + "/Recieved", filename);
        if (!file.exists()) {
            file.createNewFile();
        }

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = connection.getInputStream();
        int totalSize = connection.getContentLength();
        Long downloadedSize = (long) 0;
        byte[] buffer = new byte[1024];
        int bufferLength = 0;
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            Log.i("Progress:", "downloadedSize:" + downloadedSize + "totalSize:" + totalSize);
        }
        fileOutput.close();
        Log.d("downloadedSize", downloadedSize + " @");
        if (downloadedSize == totalSize) {
            downloadedimageuri = file.getAbsolutePath();
            return true;
        }

        if (file.exists()) {
            connection.setAllowUserInteraction(true);
            connection.setRequestProperty("Range", "bytes=" + file.length() + "-");
        }

        connection.setConnectTimeout(14000);
        connection.setReadTimeout(20000);
        connection.connect();

        if (connection.getResponseCode() / 100 != 2)
            throw new Exception("Invalid response code!");
        else {
            String connectionField = connection.getHeaderField("content-range");

            if (connectionField != null) {
                String[] connectionRanges = connectionField.substring("bytes=".length()).split("-");
                downloadedSize = Long.valueOf(connectionRanges[0]);
            }

            if (connectionField == null && file.exists())
                file.delete();

            fileLength = connection.getContentLength() + downloadedSize;
            BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
            RandomAccessFile output = new RandomAccessFile(file, "rw");
            output.seek(downloadedSize);

            byte data[] = new byte[1024];
            int count = 0;
            int __progress = 0;

            while ((count = input.read(data, 0, 1024)) != -1 && __progress != 100) {
                downloadedSize += count;
                output.write(data, 0, count);
                __progress = (int) ((downloadedSize * 100) / fileLength);
            }

            output.close();
            input.close();

        }

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return false;

}

From source file:com.limegroup.gnutella.metadata.MP3DataEditor.java

/**
 * Actually writes the ID3 tags out to the ID3V1 section of mp3 file.
 *///from w ww  .  j a v  a  2 s .co m
private int writeID3V1DataToDisk(RandomAccessFile file) {
    byte[] buffer = new byte[30];//max buffer length...drop/pickup vehicle

    //see if there are ID3 Tags in the file
    String tag = "";
    try {
        file.readFully(buffer, 0, 3);
        tag = new String(buffer, 0, 3);
    } catch (EOFException e) {
        return LimeXMLReplyCollection.RW_ERROR;
    } catch (IOException e) {
        return LimeXMLReplyCollection.RW_ERROR;
    }
    //We are sure this is an MP3 file.Otherwise this method would never
    //be called.
    if (!tag.equals("TAG")) {
        //Write the TAG
        try {
            byte[] tagBytes = "TAG".getBytes();//has to be len 3
            file.seek(file.length() - 128);//reset the file-pointer
            file.write(tagBytes, 0, 3);//write these three bytes into the File
        } catch (IOException ioe) {
            return LimeXMLReplyCollection.BAD_ID3;
        }
    }
    LOG.debug("about to start writing to file");
    boolean b;
    b = toFile(title_, 30, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_TITLE;
    b = toFile(artist_, 30, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_ARTIST;
    b = toFile(album_, 30, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_ALBUM;
    b = toFile(year_, 4, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_YEAR;
    //comment and track (a little bit tricky)
    b = toFile(comment_, 28, file, buffer);//28 bytes for comment
    if (!b)
        return LimeXMLReplyCollection.FAILED_COMMENT;

    byte trackByte = (byte) -1;//initialize
    try {
        if (track_ == null || track_.equals(""))
            trackByte = (byte) 0;
        else
            trackByte = Byte.parseByte(track_);
    } catch (NumberFormatException nfe) {
        return LimeXMLReplyCollection.FAILED_TRACK;
    }

    try {
        file.write(0);//separator b/w comment and track(track is optional)
        file.write(trackByte);
    } catch (IOException e) {
        return LimeXMLReplyCollection.FAILED_TRACK;
    }

    //genre
    byte genreByte = getGenreByte();
    try {
        file.write(genreByte);
    } catch (IOException e) {
        return LimeXMLReplyCollection.FAILED_GENRE;
    }
    //come this far means we are OK.
    return LimeXMLReplyCollection.NORMAL;

}

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 . ja  v a  2s .  co  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.limegroup.gnutella.metadata.MP3DataEditor.java

private boolean toFile(String val, int maxLen, RandomAccessFile file, byte[] buffer) {
    if (LOG.isDebugEnabled())
        LOG.debug("writing value to file " + val);
    byte[] fromString;

    if (val == null || val.equals("")) {
        fromString = new byte[maxLen];
        Arrays.fill(fromString, 0, maxLen, (byte) 0);//fill it all with 0
    } else {/*from  www  . j  a va2s .co  m*/
        try {
            fromString = val.getBytes(ISO_LATIN_1);
        } catch (UnsupportedEncodingException err) {
            // Should never happen
            return false;
        }
    }

    int len = fromString.length;
    if (len < maxLen) {
        System.arraycopy(fromString, 0, buffer, 0, len);
        Arrays.fill(buffer, len, maxLen, (byte) 0);//fill the rest with 0s
    } else//cut off the rest
        System.arraycopy(fromString, 0, buffer, 0, maxLen);

    try {
        file.write(buffer, 0, maxLen);
    } catch (IOException e) {
        return false;
    }

    return true;
}

From source file:com.replaymod.replaystudio.launcher.ReverseLauncher.java

public void launch(CommandLine cmd) throws Exception {
    ZipFile file = new ZipFile(cmd.getArgs()[0]);
    ZipEntry entry = file.getEntry("recording.tmcpr");
    if (entry == null) {
        throw new IOException("Input file is not a valid replay file.");
    }//from w w  w. j  a  v  a 2s  . c o  m
    long size = entry.getSize();
    if (size == -1) {
        throw new IOException("Uncompressed size of recording.tmcpr not set.");
    }

    InputStream from = file.getInputStream(entry);
    RandomAccessFile to = new RandomAccessFile(cmd.getArgs()[1], "rw");

    to.setLength(size);
    int nRead;
    long pos = size;
    byte[] buffer = new byte[8192];

    long lastUpdate = -1;
    while (true) {
        long pct = 100 - pos * 100 / size;
        if (lastUpdate != pct) {
            System.out.print("Reversing " + size + " bytes... " + pct + "%\r");
            lastUpdate = pct;
        }
        int next = readInt(from);
        int length = readInt(from);
        if (next == -1 || length == -1) {
            break; // reached end of stream
        }
        // Increase buffer if necessary
        if (length + 8 > buffer.length) {
            buffer = new byte[length + 8];
        }
        buffer[0] = (byte) ((next >>> 24) & 0xFF);
        buffer[1] = (byte) ((next >>> 16) & 0xFF);
        buffer[2] = (byte) ((next >>> 8) & 0xFF);
        buffer[3] = (byte) (next & 0xFF);
        buffer[4] = (byte) ((length >>> 24) & 0xFF);
        buffer[5] = (byte) ((length >>> 16) & 0xFF);
        buffer[6] = (byte) ((length >>> 8) & 0xFF);
        buffer[7] = (byte) (length & 0xFF);

        nRead = 0;
        while (nRead < length) {
            nRead += from.read(buffer, 8 + nRead, length - nRead);
        }

        pos -= length + 8;
        to.seek(pos);
        to.write(buffer, 0, length + 8);
    }

    from.close();
    to.close();

    System.out.println("\nDone!");
}