Example usage for java.io RandomAccessFile RandomAccessFile

List of usage examples for java.io RandomAccessFile RandomAccessFile

Introduction

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

Prototype

public RandomAccessFile(File file, String mode) throws FileNotFoundException 

Source Link

Document

Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.

Usage

From source file:com.thoughtworks.go.config.GoConfigDataSource.java

public synchronized GoConfigSaveResult writeWithLock(UpdateConfigCommand updatingCommand,
        GoConfigHolder configHolder) {// www. jav  a2s .  co  m
    FileChannel channel = null;
    FileOutputStream outputStream = null;
    FileLock lock = null;
    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw");
        channel = randomAccessFile.getChannel();
        lock = channel.lock();

        // Need to convert to xml before we try to write it to the config file.
        // If our cruiseConfig fails XSD validation, we don't want to write it incorrectly.
        String configAsXml = getModifiedConfig(updatingCommand, configHolder);

        randomAccessFile.seek(0);
        randomAccessFile.setLength(0);
        outputStream = new FileOutputStream(randomAccessFile.getFD());
        LOGGER.info(String.format("[Configuration Changed] Saving updated configuration."));
        IOUtils.write(configAsXml, outputStream);
        ConfigSaveState configSaveState = shouldMergeConfig(updatingCommand, configHolder)
                ? ConfigSaveState.MERGED
                : ConfigSaveState.UPDATED;
        return new GoConfigSaveResult(internalLoad(configAsXml, getConfigUpdatingUser(updatingCommand)),
                configSaveState);
    } catch (ConfigFileHasChangedException e) {
        LOGGER.warn("Configuration file could not be merged successfully after a concurrent edit: "
                + e.getMessage(), e);
        throw e;
    } catch (GoConfigInvalidException e) {
        LOGGER.warn("Configuration file is invalid: " + e.getMessage(), e);
        throw bomb(e.getMessage(), e);
    } catch (Exception e) {
        LOGGER.error("Configuration file is not valid: " + e.getMessage(), e);
        throw bomb(e.getMessage(), e);
    } finally {
        if (channel != null && lock != null) {
            try {
                lock.release();
                channel.close();
                IOUtils.closeQuietly(outputStream);
            } catch (IOException e) {
                LOGGER.error("Error occured when releasing file lock and closing file.", e);
            }
        }
        LOGGER.debug("[Config Save] Done writing with lock");
    }
}

From source file:com.ettrema.zsync.UploadMakerEx.java

/**
 * Constructs the List of DataRange objects containing the portions of the client file
 * to be uploaded to the server. Currently unused.
 * //  w ww  .  j a  v a  2s . c  om
 * @param ranges The List of Ranges from the client file needed by the server, which can be 
 * obtained from {@link #serversMissingRangesEx(List, long, int)}
 * @param local The client file to be uploaded
 * @return An InputStream containing the dataStream portion of an Upload
 * @throws IOException
 */
public static InputStream getDataRanges(List<Range> ranges, File local) throws IOException {

    int MAX_BUFFER = 1024 * 1024;

    ByteRangeWriter byteRanges = new ByteRangeWriter(MAX_BUFFER);
    RandomAccessFile randAccess = new RandomAccessFile(local, "r");

    for (Range range : ranges) {

        byteRanges.add(range, randAccess);
    }

    return byteRanges.getInputStream();
}

From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java

/**
 * Source://from   w ww. ja v a2 s  .  co m
 * http://stackoverflow.com/questions/4349075/bitmapfactory-decoderesource
 * -returns-a-mutable-bitmap-in-android-2-2-and-an-immu
 * 
 * Converts a immutable bitmap to a mutable bitmap. This operation doesn't
 * allocates more memory that there is already allocated.
 * 
 * @param imgIn
 *            - Source image. It will be released, and should not be used
 *            more
 * @return a copy of imgIn, but immutable.
 */
public static Bitmap convertBitmapToMutable(Bitmap imgIn) {
    try {
        // this is the file going to use temporally to save the bytes.
        // This file will not be a image, it will store the raw image data.
        File file = new File(MyApp.context.getFilesDir() + File.separator + "temp.tmp");

        // Open an RandomAccessFile
        // Make sure you have added uses-permission
        // android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        // into AndroidManifest.xml file
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

        // get the width and height of the source bitmap.
        int width = imgIn.getWidth();
        int height = imgIn.getHeight();
        Config type = imgIn.getConfig();

        // Copy the byte to the file
        // Assume source bitmap loaded using options.inPreferredConfig =
        // Config.ARGB_8888;
        FileChannel channel = randomAccessFile.getChannel();
        MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, imgIn.getRowBytes() * height);
        imgIn.copyPixelsToBuffer(map);
        // recycle the source bitmap, this will be no longer used.
        imgIn.recycle();
        System.gc();// try to force the bytes from the imgIn to be released

        // Create a new bitmap to load the bitmap again. Probably the memory
        // will be available.
        imgIn = Bitmap.createBitmap(width, height, type);
        map.position(0);
        // load it back from temporary
        imgIn.copyPixelsFromBuffer(map);
        // close the temporary file and channel , then delete that also
        channel.close();
        randomAccessFile.close();

        // delete the temporary file
        file.delete();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return imgIn;
}

From source file:com.aol.advertising.qiao.util.CommonUtils.java

public static long checksum(File file, int numBytes)
        throws IOException, FileNotFoundException, InterruptedException, InsufficientFileLengthException {
    RandomAccessFile raf = null;//ww w .j av  a  2 s  .c om
    try {
        raf = new RandomAccessFile(file, "r");
        long v = checksum(raf, numBytes);
        return v;
    } finally {
        IOUtils.closeQuietly(raf);
    }

}

From source file:com.qumasoft.qvcslib.CompareFilesWithApacheDiff.java

private CompareLineInfo[] buildLinesFromFile(File inFile) throws IOException {
    List<CompareLineInfo> lineInfoList = new ArrayList<>();
    RandomAccessFile randomAccessFile = new RandomAccessFile(inFile, "r");
    long fileLength = randomAccessFile.length();
    int startOfLineSeekPosition = 0;
    int currentSeekPosition = 0;
    byte character;
    while (currentSeekPosition < fileLength) {
        character = randomAccessFile.readByte();
        currentSeekPosition = (int) randomAccessFile.getFilePointer();
        if (character == '\n') {
            int endOfLine = (int) randomAccessFile.getFilePointer();
            byte[] buffer = new byte[endOfLine - startOfLineSeekPosition];
            randomAccessFile.seek(startOfLineSeekPosition);
            randomAccessFile.readFully(buffer);
            String line = new String(buffer, UTF8);
            CompareLineInfo lineInfo = new CompareLineInfo(startOfLineSeekPosition, createCompareLine(line));
            lineInfoList.add(lineInfo);/*from   ww w .  jav  a  2s.  c o m*/
            startOfLineSeekPosition = endOfLine;
        }
    }
    // Add the final line which can happen if it doesn't end in a newline.
    if ((fileLength - startOfLineSeekPosition) > 0L) {
        byte[] buffer = new byte[(int) fileLength - startOfLineSeekPosition];
        randomAccessFile.seek(startOfLineSeekPosition);
        randomAccessFile.readFully(buffer);
        String line = new String(buffer, UTF8);
        CompareLineInfo lineInfo = new CompareLineInfo(startOfLineSeekPosition, createCompareLine(line));
        lineInfoList.add(lineInfo);
    }
    CompareLineInfo[] lineInfoArray = new CompareLineInfo[lineInfoList.size()];
    int i = 0;
    for (CompareLineInfo lineInfo : lineInfoList) {
        lineInfoArray[i++] = lineInfo;
    }
    return lineInfoArray;
}

From source file:edu.rit.flick.DefaultFlickFile.java

@Override
public File inflate(final Configuration configuration, final File fileIn, final File fileOut) {
    try {/* w  w  w. j ava  2 s .  com*/
        if (!getDefaultDeflatedExtension().endsWith(Files.getFileExtension(fileIn.getName()))) {
            final File decompressedFile = archiveFile(fileIn, true);

            if (decompressedFile != null && configuration.getFlag(DELETE_FLAG))
                if (!FileUtils.deleteQuietly(fileIn))
                    System.err.printf(FILE_COULD_NOT_BE_DELETED_WARNING_FORMAT, fileIn.getPath());

            return decompressedFile;
        }

        final LongAdder unzippedContentsSize = new LongAdder();

        final long inputFileSize = FileUtils.sizeOf(fileIn);
        final long t0 = System.currentTimeMillis();

        flickFile.extractAll(fileOut.getPath());

        final RandomAccessFile raf = new RandomAccessFile(flickFile.getFile(), InternalZipConstants.READ_MODE);

        final HeaderReader hr = new HeaderReader(raf);
        final ZipModel zm = hr.readAllHeaders();
        final CentralDirectory centralDirectory = zm.getCentralDirectory();
        @SuppressWarnings("unchecked")
        final List<FileHeader> fhs = Collections.checkedList(centralDirectory.getFileHeaders(),
                FileHeader.class);

        final List<File> files = fhs.stream().map(fh -> {
            final File file = FileUtils.getFile(fileOut.getPath(), File.separator, fh.getFileName());
            unzippedContentsSize.add(file.length());
            return file;
        }).collect(Collectors.toList());

        if (!configuration.getFlag(KEEP_ZIPPED_FLAG))
            // Traverse directory and look for files to decompress
            for (final File file : files) {
                File decompressedFile = null;
                if (!file.isDirectory())
                    decompressedFile = archiveFile(file, false);

                if (decompressedFile != null) {
                    unzippedContentsSize.add(-FileUtils.sizeOf(file));
                    unzippedContentsSize.add(FileUtils.sizeOf(decompressedFile));
                    file.delete();
                }
            }

        raf.close();

        if (configuration.getFlag(DELETE_FLAG))
            if (!FileUtils.deleteQuietly(fileIn))
                System.err.printf(FILE_COULD_NOT_BE_DELETED_WARNING_FORMAT, fileIn.getPath());

        final double overallTime = (System.currentTimeMillis() - t0) / 1000d;

        if (configuration.getFlag(VERBOSE_FLAG)) {
            // Get the percent deflation on the compressed file
            final double percDeflated = 100 * unzippedContentsSize.doubleValue() / inputFileSize;

            System.out.printf(VERBOSE_DECOMPRESSION_INFO_FORMAT, fileIn.getName(), overallTime, percDeflated);
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }

    return fileOut;
}

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

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

    try {//ww  w .j  ava  2 s . co  m
        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:jm.web.Archivo.java

public String getArchivoXml(String path, String tabla, String clave, String campoNombre, String campo) {
    this._archivoNombre = "";
    try {/*  ww  w.j a  v  a 2s . c o m*/
        ResultSet res = this.consulta("select * from " + tabla + " where clave_acceso='" + clave + "'   ;");
        if (res.next()) {
            this._archivoNombre = res.getString(campoNombre) != null ? res.getString(campoNombre) : "";
            if (this._archivoNombre.compareTo("") != 0) {
                try {
                    this._archivo = new File(path, this._archivoNombre);
                    if (!this._archivo.exists()) {
                        //byte[] bytes = (res.getString(campoBytea)!=null) ? res.getBytes(campoBytea) : null;
                        RandomAccessFile archivo = new RandomAccessFile(path + this._archivoNombre + ".xml",
                                "rw");
                        archivo.writeBytes(campo);
                        archivo.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            res.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this._archivoNombre;
}

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)
 *///  www . j  ava2s . 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);
}