Example usage for java.io FileInputStream skip

List of usage examples for java.io FileInputStream skip

Introduction

In this page you can find the example usage for java.io FileInputStream skip.

Prototype

public long skip(long n) throws IOException 

Source Link

Document

Skips over and discards n bytes of data from the input stream.

Usage

From source file:jp.aegif.alfresco.online_webdav.WebDAVMethod.java

/**
 * Set the request/response details// w  ww.  j a va  2s. c o m
 * 
 * @param req
 *            HttpServletRequest
 * @param resp
 *            HttpServletResponse
 * @param registry
 *            ServiceRegistry
 * @param rootNode
 *            NodeRef
 */
public void setDetails(final HttpServletRequest req, HttpServletResponse resp, WebDAVHelper davHelper,
        NodeRef rootNode) {
    // Wrap the request so that it is 'retryable'. Calls to getInputStream() and getReader() will result in the
    // request body being read into an intermediate file.
    this.m_request = new HttpServletRequestWrapper(req) {

        @Override
        public ServletInputStream getInputStream() throws IOException {
            if (WebDAVMethod.this.m_reader != null) {
                throw new IllegalStateException("Reader in use");
            }
            if (WebDAVMethod.this.m_inputStream == null) {
                final FileInputStream in = new FileInputStream(getRequestBodyAsFile(req));
                WebDAVMethod.this.m_inputStream = new ServletInputStream() {

                    @Override
                    public int read() throws IOException {
                        return in.read();
                    }

                    @Override
                    public int read(byte b[]) throws IOException {
                        return in.read(b);
                    }

                    @Override
                    public int read(byte b[], int off, int len) throws IOException {
                        return in.read(b, off, len);
                    }

                    @Override
                    public long skip(long n) throws IOException {
                        return in.skip(n);
                    }

                    @Override
                    public int available() throws IOException {
                        return in.available();
                    }

                    @Override
                    public void close() throws IOException {
                        in.close();
                    }

                    @Override
                    public void mark(int readlimit) {
                        in.mark(readlimit);
                    }

                    @Override
                    public void reset() throws IOException {
                        in.reset();
                    }

                    @Override
                    public boolean markSupported() {
                        return in.markSupported();
                    }
                };
            }

            return WebDAVMethod.this.m_inputStream;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            if (WebDAVMethod.this.m_inputStream != null) {
                throw new IllegalStateException("Input Stream in use");
            }
            if (WebDAVMethod.this.m_reader == null) {
                String encoding = req.getCharacterEncoding();
                WebDAVMethod.this.m_reader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(getRequestBodyAsFile(req)),
                                encoding == null ? "ISO-8859-1" : encoding));
            }

            return WebDAVMethod.this.m_reader;
        }

    };
    this.m_response = resp;
    this.m_davHelper = davHelper;
    this.m_rootNodeRef = rootNode;

    this.m_strPath = m_davHelper.getRepositoryPath(m_request);
}

From source file:org.apache.hadoop.hdfs.BlockReaderLocal.java

private BlockReaderLocal(Configuration conf, String hdfsfile, Block block, Token<BlockTokenIdentifier> token,
        long startOffset, long length, BlockLocalPathInfo pathinfo, DataChecksum checksum,
        boolean verifyChecksum, FileInputStream dataIn, FileInputStream checksumIn) throws IOException {
    super(new Path("/blk_" + block.getBlockId() + ":of:" + hdfsfile) /*too non path-like?*/, 1, checksum,
            verifyChecksum);/*from  www.  jav  a2  s .c om*/
    this.startOffset = startOffset;
    this.dataIn = dataIn;
    this.checksumIn = checksumIn;
    this.checksum = checksum;

    long blockLength = pathinfo.getNumBytes();

    /* If bytesPerChecksum is very large, then the metadata file
     * is mostly corrupted. For now just truncate bytesPerchecksum to
     * blockLength.
     */
    bytesPerChecksum = checksum.getBytesPerChecksum();
    if (bytesPerChecksum > 10 * 1024 * 1024 && bytesPerChecksum > blockLength) {
        checksum = DataChecksum.newDataChecksum(checksum.getChecksumType(),
                Math.max((int) blockLength, 10 * 1024 * 1024));
        bytesPerChecksum = checksum.getBytesPerChecksum();
    }

    checksumSize = checksum.getChecksumSize();

    long endOffset = blockLength;
    if (startOffset < 0 || startOffset > endOffset || (length + startOffset) > endOffset) {
        String msg = " Offset " + startOffset + " and length " + length + " don't match block " + block
                + " ( blockLen " + endOffset + " )";
        LOG.warn("BlockReaderLocal requested with incorrect offset: " + msg);
        throw new IOException(msg);
    }

    firstChunkOffset = (startOffset - (startOffset % bytesPerChecksum));

    if (length >= 0) {
        // Make sure endOffset points to end of a checksumed chunk.
        long tmpLen = startOffset + length;
        if (tmpLen % bytesPerChecksum != 0) {
            tmpLen += (bytesPerChecksum - tmpLen % bytesPerChecksum);
        }
        if (tmpLen < endOffset) {
            endOffset = tmpLen;
        }
    }

    // seek to the right offsets
    if (firstChunkOffset > 0) {
        dataIn.getChannel().position(firstChunkOffset);

        long checksumSkip = (firstChunkOffset / bytesPerChecksum) * checksumSize;
        // note blockInStream is  seeked when created below
        if (checksumSkip > 0) {
            checksumIn.skip(checksumSkip);
        }
    }

    lastChunkOffset = firstChunkOffset;
    lastChunkLen = -1;
}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

private String gdataUpload(File file, String uploadUrl, int start, int end, Activity activity)
        throws IOException {

    mActivity = activity;/* w w  w  . ja  v  a  2s  . c o m*/

    int chunk = end - start + 1;
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    FileInputStream fileStream = new FileInputStream(file);

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);

    // some mobile proxies do not support PUT, using X-HTTP-Method-Override
    // to get around this problem
    if (isFirstRequest()) {
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded));
        urlConnection.setRequestMethod("POST");
    } else {
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.",
                (int) totalBytesUploaded));
    }
    urlConnection.setDoOutput(true);
    urlConnection.setFixedLengthStreamingMode(chunk);
    // /XXX hardcoded video mimetype
    urlConnection.setRequestProperty("Content-Type", "video/mp4");
    urlConnection.setRequestProperty("Content-Range",
            String.format("bytes %d-%d/%d", start, end, file.length()));
    Log.d(TAG, urlConnection.getRequestProperty("Content-Range"));

    OutputStream outStreamWriter = urlConnection.getOutputStream();

    fileStream.skip(start);

    int bytesRead;
    int totalRead = 0;

    Thread thread = new Thread() {

        public void run() {
            int lastPercent = 0;

            while (lastPercent < 100) {
                if (lastPercent != percentUploaded) {
                    ((SSCXferActivity) mActivity).showProgress("uploading...", percentUploaded);
                    lastPercent = percentUploaded;
                }

                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }

            }
        }
    };
    thread.start();

    while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
        outStreamWriter.write(buffer, 0, bytesRead);
        totalRead += bytesRead;
        this.totalBytesUploaded += bytesRead;

        percentUploaded = (int) (((float) totalBytesUploaded) / ((float) currentFileSize) * 99f);

        if (totalRead == (end - start + 1)) {
            break;
        }
    }

    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();

    Log.d(TAG, "responseCode=" + responseCode);
    Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage());

    try {
        if (responseCode == 201) {
            String videoId = parseVideoId(urlConnection.getInputStream());

            Log.i(TAG, "Youtube video submitted - new video id is " + videoId);

            // 100% finished here.

            // dialog.setProgress(100);

            return videoId;
        } else if (responseCode == 200) {
            Set<String> keySet = urlConnection.getHeaderFields().keySet();
            String keys = urlConnection.getHeaderFields().keySet().toString();
            Log.d(TAG, String.format("Headers keys %s.", keys));
            for (String key : keySet) {
                Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
            }
            Log.w(TAG, "Received 200 response during resumable uploading");
            throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s",
                    responseCode, urlConnection.getResponseMessage()));
        } else {
            if ((responseCode + "").startsWith("5")) {
                String error = String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage());
                Log.w(TAG, error);
                // TODO - this exception will trigger retry mechanism to
                // kick in
                // TODO - even though it should not, consider introducing a
                // new type so
                // TODO - resume does not kick in upon 5xx
                throw new IOException(error);
            } else if (responseCode == 308) {
                // OK, the chunk completed successfully
                Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage()));
            } else {
                // TODO - this case is not handled properly yet
                Log.w(TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
                        urlConnection.getResponseMessage(), uploadUrl));
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.BeatYourRecord.SubmitActivity.java

private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException {
    int chunk = end - start + 1;
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    FileInputStream fileStream = new FileInputStream(file);

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    // some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem
    if (isFirstRequest()) {
        Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded));
        urlConnection.setRequestMethod("POST");
    } else {/*w  w  w .j  a va2 s . c  o m*/
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
        Log.d(LOG_TAG,
                String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.",
                        (int) totalBytesUploaded));
    }
    urlConnection.setDoOutput(true);
    urlConnection.setFixedLengthStreamingMode(chunk);
    urlConnection.setRequestProperty("Content-Type", "video/3gpp");
    urlConnection.setRequestProperty("Content-Range",
            String.format("bytes %d-%d/%d", start, end, file.length()));
    Log.d(LOG_TAG, urlConnection.getRequestProperty("Content-Range"));
    //////may be
    //log.v("id man id",urlConnection.getRequestProperty("Content-Range"));
    OutputStream outStreamWriter = urlConnection.getOutputStream();

    fileStream.skip(start);

    int bytesRead;
    int totalRead = 0;
    while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
        outStreamWriter.write(buffer, 0, bytesRead);
        totalRead += bytesRead;
        this.totalBytesUploaded += bytesRead;

        double percent = (totalBytesUploaded / currentFileSize) * 99;

        /*
        Log.d(LOG_TAG, String.format(
        "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize,
        totalBytesUploaded, percent));
        */

        dialog.setProgress((int) percent);

        if (totalRead == (end - start + 1)) {
            break;
        }
    }

    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();

    Log.d(LOG_TAG, "responseCode=" + responseCode);
    Log.d(LOG_TAG, "responseMessage=" + urlConnection.getResponseMessage());

    try {
        if (responseCode == 201) {
            String videoId = parseVideoId(urlConnection.getInputStream());
            //log.v("Video ID", videoId);
            vidId = videoId;
            String latLng = null;
            if (this.videoLocation != null) {
                latLng = String.format("lat=%f lng=%f", this.videoLocation.getLatitude(),
                        this.videoLocation.getLongitude());
            }

            submitToYtdDomain(this.ytdDomain, this.assignmentId, videoId, this.youTubeName,
                    SubmitActivity.this.clientLoginToken, getTitleText(), getDescriptionText(), this.dateTaken,
                    latLng, this.tags);
            dialog.setProgress(100);
            //log.v("10video id",videoId);
            return videoId;
        } else if (responseCode == 200) {
            Set<String> keySet = urlConnection.getHeaderFields().keySet();
            String keys = urlConnection.getHeaderFields().keySet().toString();
            Log.d(LOG_TAG, String.format("Headers keys %s.", keys));
            //////////////may be
            for (String key : keySet) {
                Log.d(LOG_TAG,
                        String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
            }
            Log.w(LOG_TAG, "Received 200 response during resumable uploading");
            throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s",
                    responseCode, urlConnection.getResponseMessage()));
        } else {
            if ((responseCode + "").startsWith("5")) {
                String error = String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage());
                Log.w(LOG_TAG, error);
                // TODO - this exception will trigger retry mechanism to kick in
                // TODO - even though it should not, consider introducing a new type so
                // TODO - resume does not kick in upon 5xx
                throw new IOException(error);
            } else if (responseCode == 308) {
                // OK, the chunk completed succesfully 
                Log.d(LOG_TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage()));
            } else {
                // TODO - this case is not handled properly yet
                Log.w(LOG_TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
                        urlConnection.getResponseMessage(), uploadUrl));
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException {
    int chunk = end - start + 1;
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    FileInputStream fileStream = new FileInputStream(file);

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    // some mobile proxies do not support PUT, using X-HTTP-Method-Override
    // to get around this problem
    if (isFirstRequest()) {
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded));
        urlConnection.setRequestMethod("POST");
    } else {//from  w w w.  ja  v  a  2  s .c  o  m
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.",
                (int) totalBytesUploaded));
    }
    urlConnection.setDoOutput(true);
    urlConnection.setFixedLengthStreamingMode(chunk);
    // /XXX hardcoded video mimetype
    urlConnection.setRequestProperty("Content-Type", "video/mp4");
    urlConnection.setRequestProperty("Content-Range",
            String.format("bytes %d-%d/%d", start, end, file.length()));
    Log.d(TAG, urlConnection.getRequestProperty("Content-Range"));

    OutputStream outStreamWriter = urlConnection.getOutputStream();

    fileStream.skip(start);

    int bytesRead;
    int totalRead = 0;
    while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
        outStreamWriter.write(buffer, 0, bytesRead);
        totalRead += bytesRead;
        this.totalBytesUploaded += bytesRead;

        // double percent = (totalBytesUploaded / currentFileSize) * 99;

        /*
         * Log.d(TAG, String.format(
         * "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize,
         * totalBytesUploaded, percent));
         */

        if (totalRead == (end - start + 1)) {
            break;
        }
    }

    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();

    Log.d(TAG, "responseCode=" + responseCode);
    Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage());

    try {
        if (responseCode == 201) {
            String videoId = parseVideoId(urlConnection.getInputStream());

            Log.i(TAG, "Youtube video submitted - new video id is " + videoId);

            // 100% finished here.

            // dialog.setProgress(100);

            return videoId;
        } else if (responseCode == 200) {
            Set<String> keySet = urlConnection.getHeaderFields().keySet();
            String keys = urlConnection.getHeaderFields().keySet().toString();
            Log.d(TAG, String.format("Headers keys %s.", keys));
            for (String key : keySet) {
                Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
            }
            Log.w(TAG, "Received 200 response during resumable uploading");
            throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s",
                    responseCode, urlConnection.getResponseMessage()));
        } else {
            if ((responseCode + "").startsWith("5")) {
                String error = String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage());
                Log.w(TAG, error);
                // TODO - this exception will trigger retry mechanism to
                // kick in
                // TODO - even though it should not, consider introducing a
                // new type so
                // TODO - resume does not kick in upon 5xx
                throw new IOException(error);
            } else if (responseCode == 308) {
                // OK, the chunk completed successfully
                Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage()));
            } else {
                // TODO - this case is not handled properly yet
                Log.w(TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
                        urlConnection.getResponseMessage(), uploadUrl));
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:gephi.spade.panel.fcsFile.java

/**
 * readFile ---/*  www.jav  a 2s. c o  m*/
 * <p>
 * A helper function to read all the fields in the TEXT segment of the FCS
 * file.
 * </p>
 *
 * <p>
 * This helper function should only be called once by the constructor as it
 * is quite expensive.
 * </p>
 *
 * @param extractEventsP
 *            boolean flag indicating whether to extract events in the
 *            underlying file.
 * @throws <code>java.io.FileNotFoundException</code> if the file is not
 *         found.
 * @throws <code>java.io.IOException</code> if an IO exception occurred.
 */
private void readFile(boolean extractEventsP) throws FileNotFoundException, IOException {
    // Open a file input stream to the file
    FileInputStream fis = new FileInputStream(file);

    // Create a byte array to hold the version
    byte[] versionArray = new byte[VERSION_SIZE];

    // Read the version into the byte array
    int numRead = fis.read(versionArray);

    if (numRead < VERSION_SIZE) {
        // If the number of bytes read is less than the number of bytes in
        // the version string, then the file is too small to be an FCS file.
        isFCSP = false;

        // Close the file input stream
        fis.close();

        // Quit
        return;
    }

    // Decode the version using the default encoding
    version = new String(versionArray);

    // Determine whether the file is an FCS file by whether the version
    // string starts with the FCS_PREFIX
    isFCSP = version.startsWith(FCS_PREFIX);

    if (!isFCSP) {
        // If the file is not an FCS file, then close the file and quit.
        // Close the file input stream
        fis.close();

        // Quit
        return;
    }

    /**
     * At this point, we are pretty sure that the file is an FCS file. So,
     * we parse it.
     */
    /**
     * Get the standard HEADER stuff
     */
    // Skip 4 bytes to get to byte 10
    fis.skip(4);

    // Create a byte array to hold the HEADER
    byte[] headerArray = new byte[48];

    // Read the header into the byte array
    numRead = fis.read(headerArray);

    if (numRead < 48) {
        // If the number of bytes read is less than 48, then the file is too
        // small to be an FCS file.
        isFCSP = false;

        // Close the file input stream
        fis.close();

        // Quit
        return;
    }

    try {
        // Try to parse the TEXT segment start and end and DATA segment
        // start and end
        textStart = Integer.parseInt((new String(headerArray, 0, 8)).trim());
        textEnd = Integer.parseInt((new String(headerArray, 8, 8)).trim());
        dataStart = Integer.parseInt((new String(headerArray, 16, 8)).trim());
        dataEnd = Integer.parseInt((new String(headerArray, 24, 8)).trim());
    } catch (NumberFormatException nfe) {
        // If a NumberFormatException occured, then quit because there's
        // nothing we can do without the TEXT or DATA segment.
        // Close the file input stream
        fis.close();

        return;
    }

    /**
     * Get the ANALYSIS segment limits
     */
    try {
        // Try to parse the analysisStart and analysisEnd
        analysisStart = Integer.parseInt((new String(headerArray, 32, 8)).trim());
        analysisEnd = Integer.parseInt((new String(headerArray, 40, 8)).trim());
    } catch (NumberFormatException nfe) {
        // If a NumberFormatException occured, then set the ANALYSIS start
        // and end to 0 since this segment is optional.
        analysisStart = 0;
        analysisEnd = 0;
    }

    /**
     * Use NIO to read the OTHER and TEXT segments
     */
    // Get the channel for the input file
    FileChannel fc = fis.getChannel();

    // Move the channel's position back to 0
    fc.position(0);

    // Map the TEXT segment to memory
    MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, textEnd + 1);

    /**
     * Create the character decoder for parsing characters
     */
    decoder = charset.newDecoder();

    /**
     * Get the OTHER segment
     */
    mbb.limit(textStart);
    mbb.position(58);
    CharBuffer other = decoder.decode(mbb.slice());

    /**
     * Get the TEXT segment
     */
    mbb.limit(textEnd + 1);
    mbb.position(textStart);
    text = decoder.decode(mbb.slice()).toString();

    /**
     * Close the file since we have the string version of the TEXT segment
     */
    // Close the file channel
    fc.close();

    // Close the file input stream
    fis.close();

    /**
     * Decode the TEXT segment
     */
    // The first character of the primary TEXT segment contains the
    // delimiter character
    delimiter = text.charAt(0);

    /**
     * Key/Value Pairs
     */
    // Generate all the pairs
    String[] pairs;

    if (delimiter == '\\') {
        // If the delimiter character is a backslash, then we have to escape
        // it in the regular expression.
        pairs = text.split("[\\\\]");
    } else {
        // Otherwise, we can just split it normally by using the character
        // in the regular expression.
        pairs = text.split("[" + Character.toString(delimiter) + "]");
    }

    /**
     * Calculate the number of pairs --- The number of pairs is the length
     * of the pairs array minus 1 divided by 2. The one is due to the empty
     * first element from the Java split above.
     */
    int numPairs = (pairs.length - 1) / 2;

    // Create a mapping for each key and its value
    settings = new Properties();

    // Loop through the TEXT segment we just split to get the keys and
    // values
    // The key is in (i * 2) + 1 to account for the empty first element.
    // The value is in (i * 2) + 2 to account for the empty first element.
    for (int i = 0; i < numPairs; i++) {
        settings.setProperty(pairs[(i * 2) + 1].trim(), pairs[(i * 2) + 2].trim());
    }

    // Go through all the key/value pairs and parse them
    parseSettings();

    /**
     * Extract Events
     */
    if (extractEventsP) {
        // If we are extracting data, then do so.
        extractEvents();
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String Pull(String fileName, long lOffset, long lLength, OutputStream out) {
    String sTmpFileName = fixFileName(fileName);
    String sRet = sErrorPrefix + "Could not read the file " + sTmpFileName;
    byte[] buffer = new byte[4096];
    int nRead = 0;
    long lSent = 0;

    if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;//from w  w  w. j  a  v a2 s  .c  o  m

        ffxFiles = Uri
                .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file");

        String[] columns = new String[] { "_id", "chunk", "length" };

        String[] args = new String[2];
        args[0] = Long.toString(lOffset);
        args[1] = Long.toString(lLength);

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpFileName, // Which rows to return (all rows)
                args, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            long lFileLength = 0;

            for (int lcv = 0; lcv < nRows; lcv++) {
                if (myCursor.moveToPosition(lcv)) {
                    if (lcv == 0) {
                        lFileLength = myCursor.getLong(2);
                        String sTmp = sTmpFileName + "," + lFileLength + "\n";
                        try {
                            out.write(sTmp.getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                            break;
                        }
                    }

                    if (lLength != 0) {
                        byte[] buf = myCursor.getBlob(1);
                        if (buf != null) {
                            nRead = buf.length;
                            try {
                                if ((lSent + nRead) <= lFileLength) {
                                    out.write(buf, 0, nRead);
                                    lSent += nRead;
                                } else {
                                    nRead = (int) (lFileLength - lSent);
                                    out.write(buf, 0, nRead);
                                    Log.d("pull warning", "more bytes read than expected");
                                    break;
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                                sRet = sErrorPrefix + "Could not write to out " + sTmpFileName;
                            }
                            buf = null;
                        }
                    }
                }
            }
            if (nRows == 0) {
                String sTmp = sTmpFileName + "," + lFileLength + "\n";
                try {
                    out.write(sTmp.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (nRows == -1) {
                sRet = sErrorPrefix + sTmpFileName + ",-1\nNo such file or directory";
            } else {
                myCursor.close();
                sRet = "";
            }
        } else {
            sRet = sErrorPrefix + sTmpFileName + ",-1\nUnable to access file (internal error)";
        }
    } else {
        try {
            File f = new File(sTmpFileName);
            long lFileLength = f.length();
            FileInputStream fin = new FileInputStream(f);
            if (lFileLength == 0) {
                while ((nRead = fin.read(buffer)) != -1) {
                    lFileLength += nRead;
                }
                fin.close();
                fin = new FileInputStream(f);
            }

            // lLength == -1 return everything between lOffset and eof
            // lLength == 0 return file length
            // lLength > 0 return lLength bytes
            if (lLength == -1) {
                lFileLength = lFileLength - lOffset;
            } else if (lLength == 0) {
                // just return the file length
            } else {
                lFileLength = ((lLength <= (lFileLength - lOffset)) ? lLength : (lFileLength - lOffset));
            }

            String sTmp = sTmpFileName + "," + lFileLength + "\n";
            out.write(sTmp.getBytes());
            if (lLength != 0) {
                if (lOffset > 0) {
                    fin.skip(lOffset);
                }
                while ((nRead = fin.read(buffer)) != -1) {
                    if ((lSent + nRead) <= lFileLength) {
                        out.write(buffer, 0, nRead);
                        lSent += nRead;
                    } else {
                        nRead = (int) (lFileLength - lSent);
                        out.write(buffer, 0, nRead);
                        if (lLength != -1)
                            Log.d("pull warning", "more bytes read than sent");
                        break;
                    }
                }
            }
            fin.close();
            out.flush();
            sRet = "";
        } catch (FileNotFoundException e) {
            sRet = sErrorPrefix + sTmpFileName + ",-1\nNo such file or directory";
        } catch (IOException e) {
            sRet = e.toString();
        }
    }
    return (sRet);
}