Example usage for java.io RandomAccessFile read

List of usage examples for java.io RandomAccessFile read

Introduction

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

Prototype

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

Source Link

Document

Reads up to len bytes of data from this file into an array of bytes.

Usage

From source file:org.slc.sli.api.resources.FileResource.java

/**
 * Send a range content// w  ww. j  a  va 2s  .  c om
 *
 * @param raf    the file from which the content is sent
 * @param output the output to which the content is sent
 * @param r      the range
 * @return       total length sent
 * @throws IOException
 */
private long sendRangeContent(RandomAccessFile raf, OutputStream output, Range r) throws IOException {

    raf.seek(r.start);
    byte[] buffer = new byte[4 * 1024];
    long left = r.getLength();
    long total = 0;
    int n = -1;

    while (left > 0 && (n = raf.read(buffer, 0, (int) Math.min(left, buffer.length))) > -1) {
        output.write(buffer, 0, n);
        output.flush();
        left -= n;
        total += n;
    }
    return total;
}

From source file:org.ngrinder.perftest.service.AgentManager.java

@Override
public synchronized AgentUpdateGrinderMessage onAgentDownloadRequested(String version, int offset) {
    final int updateChunkSize = getUpdateChunkSize();
    byte[] buffer = new byte[updateChunkSize];
    RandomAccessFile agentPackageReader = null;
    try {/* w  ww .  j  a  va2  s.  c om*/
        agentPackageReader = new RandomAccessFile(agentPackageService.createAgentPackage(), "r");
        agentPackageReader.seek(offset);
        int count = agentPackageReader.read(buffer, 0, updateChunkSize);
        byte[] bytes = buffer;
        int next = offset + count;
        if (count != updateChunkSize) {
            bytes = Arrays.copyOf(buffer, count);
            next = 0;
        }
        return new AgentUpdateGrinderMessage(version, bytes, offset, next,
                CRC32ChecksumUtils.getCRC32Checksum(bytes));
    } catch (Exception e) {
        LOGGER.error("Error while reading agent package, its offset is {} and details {}:", offset, e);
    } finally {
        IOUtils.closeQuietly(agentPackageReader);
    }
    return AgentUpdateGrinderMessage.getNullAgentUpdateGrinderMessage(version);
}

From source file:ape.CorruptCommand.java

/**
 * This method is the implementation of the corrupt function.
 * Given an address, it corrupts the file in the given address
 *//*from   w w w.j a  v  a 2 s  . co  m*/
public boolean corrupt(String corruptAddress) throws IOException {
    // Trying to get a random HDFS block file
    if (Main.VERBOSE) {
        System.out.println("Trying to get a random HDFS block file");
    }
    if (corruptAddress == null) {
        corruptAddress = getCorruptAddress();
    }

    // If the above statement failed to set corruptAddress then there was a failure
    if (corruptAddress == null) {
        System.out.println("Could not get a random HDFS block file");
        Main.logger.info("Could not get a random HDFS block file");
        return false;
    }

    byte[] buf;
    int count;

    try {
        RandomAccessFile tmp = new RandomAccessFile(corruptAddress, "rw");
        tmp.seek(offset);
        if (size <= 0) {
            System.out.println("ERROR: The size parameter must be positive");
            Main.logger.info("ERROR: The size parameter must be positive");
            return false;
        }

        buf = new byte[size];

        count = 0;
        if ((count = tmp.read(buf, 0, size)) == -1) {
            System.out.println("The file chosen is smaller than the corruption size (" + size + " bytes)");
            Main.logger.info("The file chosen is smaller than the corruption size (" + size + " bytes)");
            return false;
        }

        for (int i = 0; i < count; i++) {
            buf[i] = 0x3;
        }

        tmp.seek(0);
        tmp.close();
    } catch (FileNotFoundException e1) {
        System.out.println("Cannot open the file on the path given");
        Main.logger.info("Cannot open the file on the path given");
        e1.printStackTrace();
        Main.logger.info(e1);
        return false;
    } catch (IOException e) {
        System.out.println("Corrupting file failed");
        Main.logger.info("Corrupting file failed");
        e.printStackTrace();
        Main.logger.info(e);
        return false;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(corruptAddress, "rw");
        raf.seek(offset);
        raf.write(buf, 0, count);
        raf.seek(0);
        raf.close();

        return true;
    } catch (FileNotFoundException e1) {
        System.out.println("Cannot open the file on the path: " + corruptAddress);
        Main.logger.info("Cannot open the file on the path: " + corruptAddress);
        e1.printStackTrace();
        Main.logger.info(e1);
        return false;
    } catch (IOException e) {
        System.out.println("Corrupting file failed");
        Main.logger.info("Corrupting file failed");
        e.printStackTrace();
        Main.logger.info(e);
        return false;
    }
}

From source file:com.metamesh.opencms.rfs.RfsAwareDumpLoader.java

/**
 * @see org.opencms.loader.I_CmsResourceLoader#load(org.opencms.file.CmsObject, org.opencms.file.CmsResource, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from  w w  w  . jav a  2 s. c  o m*/
public void load(CmsObject cms, CmsResource resource, HttpServletRequest req, HttpServletResponse res)
        throws IOException, CmsException {

    if (!(resource instanceof RfsCmsResource)) {
        super.load(cms, resource, req, res);
        return;
    }

    if (canSendLastModifiedHeader(resource, req, res)) {
        // no further processing required
        return;
    }

    if (CmsWorkplaceManager.isWorkplaceUser(req)) {
        // prevent caching for Workplace users
        res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis());
        CmsRequestUtil.setNoCacheHeaders(res);
    }

    RfsCmsResource rfsFile = (RfsCmsResource) resource;
    File f = rfsFile.getRfsFile();

    if (f.getName().toLowerCase().endsWith("webm")) {
        res.setHeader("Content-Type", "video/webm");
    } else if (f.getName().toLowerCase().endsWith("ogv")) {
        res.setHeader("Content-Type", "video/ogg");
    } else if (f.getName().toLowerCase().endsWith("mp4")) {
        res.setHeader("Content-Type", "video/mp4");
    }

    if (req.getMethod().equalsIgnoreCase("HEAD")) {
        res.setStatus(HttpServletResponse.SC_OK);
        res.setHeader("Accept-Ranges", "bytes");
        res.setContentLength((int) f.length());
        return;
    } else if (req.getMethod().equalsIgnoreCase("GET")) {
        if (req.getHeader("Range") != null) {

            String range = req.getHeader("Range");

            String[] string = range.split("=")[1].split("-");
            long start = Long.parseLong(string[0]);
            long end = string.length == 1 ? f.length() - 1 : Long.parseLong(string[1]);
            long length = end - start + 1;

            res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

            res.setHeader("Accept-Ranges", "bytes");
            res.setHeader("Content-Length", "" + length);
            res.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + f.length());

            RandomAccessFile ras = null;

            try {
                ras = new RandomAccessFile(f, "r");
                ras.seek(start);
                final int chunkSize = 4096;
                byte[] buffy = new byte[chunkSize];
                int nextChunkSize = length > chunkSize ? chunkSize : (int) length;
                long bytesLeft = length;
                while (bytesLeft > 0) {
                    ras.read(buffy, 0, nextChunkSize);
                    res.getOutputStream().write(buffy, 0, nextChunkSize);
                    res.getOutputStream().flush();
                    bytesLeft = bytesLeft - nextChunkSize;
                    nextChunkSize = bytesLeft > chunkSize ? chunkSize : (int) bytesLeft;

                    /*
                     * to simulate lower bandwidth
                     */
                    /*
                    try {
                      Thread.sleep(10);
                    } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                    }
                    */
                }
            } finally {
                if (ras != null) {
                    ras.close();
                }
            }
            return;
        }
    }

    res.setStatus(HttpServletResponse.SC_OK);
    res.setHeader("Accept-Ranges", "bytes");
    res.setContentLength((int) f.length());
    service(cms, resource, req, res);
}

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

/**
 * Read and decrypt the section starting at the current file offset.
 * Validates MAC of decrypted data, throwing if mismatch. When finished,
 * file offset is at the end of the entire section.
 */// ww  w  . ja  v  a2 s.  c  o  m
private void readSection(RandomAccessFile f, OutputStream out) throws IOException, GeneralSecurityException {
    final long start = f.getFilePointer();

    final Section section = new Section();
    section.read(f);

    final IvParameterSpec ivSpec = new IvParameterSpec(section.iv);
    mCipher.init(Cipher.DECRYPT_MODE, mDataKey, ivSpec);
    mMac.init(mMacKey);

    byte[] inbuf = new byte[8192];
    byte[] outbuf;
    int n;
    while ((n = f.read(inbuf, 0, (int) Math.min(section.length, inbuf.length))) != -1) {
        section.length -= n;
        mMac.update(inbuf, 0, n);
        outbuf = mCipher.update(inbuf, 0, n);
        if (outbuf != null) {
            out.write(outbuf);
        }
        if (section.length == 0)
            break;
    }

    section.assertMac(mMac.doFinal());

    outbuf = mCipher.doFinal();
    if (outbuf != null) {
        out.write(outbuf);
    }
}

From source file:pydio.sdk.java.http.AjxpFileBody.java

public void writeTo(OutputStream out) {

    InputStream in;//from w  ww.j  a  v a2  s. c  om
    //int bufsize = Integer.parseInt(StateHolder.getInstance().getLocalConfig(Pydio.LOCAL_CONFIG_BUFFER_SIZE));

    try {
        if (this.chunkSize > 0) {
            RandomAccessFile raf = new RandomAccessFile(getFile(), "r");
            int start = chunkIndex * this.chunkSize;

            int count = 0;
            int limit = chunkSize;
            byte[] buffer = new byte[bufsize];

            if (chunkIndex == (totalChunks - 1)) {
                limit = lastChunkSize;
            }

            raf.seek(start);

            while (count < limit) {

                if (count + bufsize > limit) {
                    if (count == 0) {
                        bufsize = limit;
                    } else {
                        bufsize = limit - count;
                    }
                }

                raf.read(buffer, 0, bufsize);
                out.write(buffer, 0, bufsize);
                count += bufsize;
            }
            raf.close();
        } else {
            in = new FileInputStream(getFile());
            byte[] buf = new byte[bufsize];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
        }
        this.chunkIndex++;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.microsoft.azure.management.datalake.store.uploader.SingleSegmentUploader.java

/**
 * Reads the data into the buffer./*from   ww w  .  ja va2  s . c o  m*/
 *
 * @param inputStream The stream to read data from.
 * @param buffer The buffer to read data into
 * @param bufferOffset The offset in the buffer to begin pushing data
 * @param streamEndPosition The last point in the stream to read.
 * @return The number of bytes read into the buffer.
 * @throws IOException Thrown if there is an issue accessing the stream or the pointer to the file.
 */
private int readIntoBuffer(RandomAccessFile inputStream, byte[] buffer, int bufferOffset,
        long streamEndPosition) throws IOException {
    //read a block of data
    int bytesToRead = buffer.length - bufferOffset;
    if (bytesToRead > streamEndPosition - inputStream.getFilePointer()) {
        //last read may be smaller than previous reads; readjust # of bytes to read accordingly
        bytesToRead = (int) (streamEndPosition - inputStream.getFilePointer());
    }

    int remainingBytes = bytesToRead;

    while (remainingBytes > 0) {
        //Stream.Read may not read all the bytes we requested, so we need to retry until we filled up the entire buffer
        int bytesRead = inputStream.read(buffer, bufferOffset, remainingBytes);
        bufferOffset += bytesRead;
        remainingBytes = bytesToRead - bufferOffset;
    }

    return bytesToRead;
}

From source file:org.openmeetings.servlet.outputhandler.ExportToImage.java

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {/*  w w  w  . j  av  a2 s .c om*/
        if (getUserManagement() == null || getSessionManagement() == null || getGenerateImage() == null) {
            return;
        }

        String sid = httpServletRequest.getParameter("sid");
        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        String hash = httpServletRequest.getParameter("hash");
        if (hash == null) {
            hash = "";
        }
        log.debug("hash: " + hash);

        String fileName = httpServletRequest.getParameter("fileName");
        if (fileName == null) {
            fileName = "file_xyz";
        }

        String exportType = httpServletRequest.getParameter("exportType");
        if (exportType == null) {
            exportType = "svg";
        }

        Long users_id = getSessionManagement().checkSession(sid);
        Long user_level = getUserManagement().getUserLevelByID(users_id);

        log.debug("users_id: " + users_id);
        log.debug("user_level: " + user_level);

        if (user_level != null && user_level > 0 && hash != "") {

            PrintBean pBean = PrintService.getPrintItemByHash(hash);

            // Whiteboard Objects
            @SuppressWarnings("rawtypes")
            List whiteBoardMap = pBean.getMap();

            // Get a DOMImplementation.
            DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();

            // Create an instance of org.w3c.dom.Document.
            // String svgNS = "http://www.w3.org/2000/svg";
            String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;

            Document document = domImpl.createDocument(svgNS, "svg", null);

            // Get the root element (the 'svg' element).
            Element svgRoot = document.getDocumentElement();

            // Set the width and height attributes on the root 'svg'
            // element.
            svgRoot.setAttributeNS(null, "width", "" + pBean.getWidth());
            svgRoot.setAttributeNS(null, "height", "" + pBean.getHeight());

            log.debug("pBean.getWidth(),pBean.getHeight()" + pBean.getWidth() + "," + pBean.getHeight());

            // Create an instance of the SVG Generator.
            SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

            svgGenerator = WhiteboardMapToSVG.getInstance().convertMapToSVG(svgGenerator, whiteBoardMap);

            // Finally, stream out SVG to the standard output using
            // UTF-8 encoding.
            boolean useCSS = true; // we want to use CSS style attributes
            // Writer out = new OutputStreamWriter(System.out, "UTF-8");

            if (exportType.equals("svg")) {
                // OutputStream out = httpServletResponse.getOutputStream();
                // httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
                // httpServletResponse.setHeader("Content-Disposition","attachment; filename=\""
                // + requestedFile + "\"");
                Writer out = httpServletResponse.getWriter();

                svgGenerator.stream(out, useCSS);

            } else if (exportType.equals("png") || exportType.equals("jpg") || exportType.equals("gif")
                    || exportType.equals("tif") || exportType.equals("pdf")) {

                String current_dir = getServletContext().getRealPath("/");
                String working_dir = current_dir + OpenmeetingsVariables.UPLOAD_TEMP_DIR + File.separatorChar;

                String requestedFileSVG = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date())
                        + ".svg";
                String resultFileName = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date()) + "."
                        + exportType;

                log.debug("current_dir: " + current_dir);
                log.debug("working_dir: " + working_dir);
                log.debug("requestedFileSVG: " + requestedFileSVG);
                log.debug("resultFileName: " + resultFileName);

                File svgFile = new File(working_dir + requestedFileSVG);
                File resultFile = new File(working_dir + resultFileName);

                log.debug("svgFile: " + svgFile.getAbsolutePath());
                log.debug("resultFile: " + resultFile.getAbsolutePath());
                log.debug("svgFile P: " + svgFile.getPath());
                log.debug("resultFile P: " + resultFile.getPath());

                FileWriter out = new FileWriter(svgFile);
                svgGenerator.stream(out, useCSS);

                // Get file and handle download
                RandomAccessFile rf = new RandomAccessFile(resultFile.getAbsoluteFile(), "r");

                httpServletResponse.reset();
                httpServletResponse.resetBuffer();
                OutputStream outStream = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
                httpServletResponse.setHeader("Content-Disposition",
                        "attachment; filename=\"" + resultFileName + "\"");
                httpServletResponse.setHeader("Content-Length", "" + rf.length());

                byte[] buffer = new byte[1024];
                int readed = -1;

                while ((readed = rf.read(buffer, 0, buffer.length)) > -1) {
                    outStream.write(buffer, 0, readed);
                }
                outStream.close();
                rf.close();

                out.flush();
                out.close();

            }

        }

    } catch (Exception er) {
        log.error("ERROR ", er);
        System.out.println("Error exporting: " + er);
        er.printStackTrace();
    }
}

From source file:org.i_chera.wolfensteineditor.document.VSwapContainer.java

/**
 * Loads data from a file. Only finishes it on success
 * @param file the VSWAP.WL6 file to load
 * @return true on success/*from   ww  w .ja  v a  2s. c  om*/
 */
public boolean loadFile(File file) {
    RandomAccessFile raf = null;
    try {
        if (file.isDirectory())
            return false;
        raf = new RandomAccessFile(file, "r");

        int newNumChunks = FileUtil.readUInt16(raf);
        int newSpriteStart = FileUtil.readUInt16(raf);
        int newSoundStart = FileUtil.readUInt16(raf);

        int[] pageOffsets = new int[newNumChunks + 1];
        for (int i = 0; i < newNumChunks; ++i)
            pageOffsets[i] = FileUtil.readInt32(raf);

        int[] pageLengths = new int[newNumChunks];
        for (int i = 0; i < newNumChunks; ++i)
            pageLengths[i] = FileUtil.readUInt16(raf);

        pageOffsets[newNumChunks] = (int) file.length();

        ArrayList<byte[]> newPages = new ArrayList<byte[]>();

        byte[] reading;
        for (int i = 0; i < newNumChunks; ++i) {
            if (pageOffsets[i] == 0) {
                reading = new byte[0];
                newPages.add(reading);
                continue;
            }
            int size;
            if (pageOffsets[i + 1] == 0)
                size = pageLengths[i];
            else
                size = pageOffsets[i + 1] - pageOffsets[i];

            raf.seek(pageOffsets[i]);
            reading = new byte[size];
            raf.read(reading, 0, size);
            newPages.add(reading);
        }

        // okay
        mNumChunks = newNumChunks;
        mSpriteStart = newSpriteStart;
        mSoundStart = newSoundStart;
        mPages = newPages;

    } catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace();
        return false;
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return false;
    } finally {
        try {
            if (raf != null)
                raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return true;
}

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 {/*w w  w.j av a  2 s .c  o m*/
        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;
}