Example usage for java.io RandomAccessFile close

List of usage examples for java.io RandomAccessFile close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this random access file stream and releases any system resources associated with the stream.

Usage

From source file:omero.util.TempFileManager.java

/**
 * Returns a platform-specific user-writable temporary directory.
 *
 * First, the value of "OMERO_TEMPDIR" is attempted (if available),
 * then user's home ("user.home") directory, then the global temp director
 * ("java.io.tmpdir")./*from ww w.  j  av  a  2  s.  com*/
 *
 * Typical errors for any of the possible temp locations are:
 * <ul>
 * <li>non-existence</li>
 * <li>inability to lock</li>
 * </ul>
 *
 * @see <a href="https://trac.openmicroscopy.org.uk/omero/ticket/1653">ticket:1653</a>
 */
protected File tmpdir() {

    File locktest = null;

    String omerotmp = System.getenv().get("OMERO_TEMPDIR");
    String homeprop = System.getProperty("user.home", null);
    String tempprop = System.getProperty("java.io.tmpdir", null);
    List<String> targets = Arrays.asList(omerotmp, homeprop, tempprop);

    for (String target : targets) {

        if (target == null) {
            continue;
        }

        RandomAccessFile raftest = null;
        try {
            File testdir = new File(target);
            locktest = File.createTempFile("._omero_util_TempFileManager_lock_test", ".tmp", testdir);
            locktest.delete();

            raftest = new RandomAccessFile(locktest, "rw");

            FileLock channeltest = raftest.getChannel().tryLock();
            channeltest.release();
        } catch (Exception e) {
            if ("Operation not permitted".equals(e.getMessage())
                    || "Operation not supported".equals(e.getMessage())) {
                // This is the issue described in ticket:1653
                // To prevent printing the warning, we just continue
                // here.
                log.debug(target + " does not support locking.");
            } else {
                log.warn("Invalid tmp dir: " + target, e);
            }
            continue;
        } finally {
            if (locktest != null && raftest != null) {
                try {
                    raftest.close();
                    locktest.delete();
                } catch (Exception e) {
                    log.warn("Failed to close/delete lock file: " + locktest);
                }
            }
        }

        log.debug("Chose global tmpdir:  " + locktest.getParent());
        break; // Something found!

    }

    if (locktest == null) {
        throw new RuntimeException("Could not find lockable tmp dir");
    }

    File omero = new File(locktest.getParentFile(), "omero");
    File tmp = new File(omero, "tmp");
    return tmp;
}

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

private boolean updateINIOnJDKUpgrade(String javaHome) {
    logger.debug("Updating INI file if JDK path is updated");
    RandomAccessFile file = null;
    boolean isUpdated = false;
    try {//from w  ww  .  ja  v a2s  . c o  m
        file = new RandomAccessFile(new File(HYDROGRAPH_INI), "rw");
        byte[] text = new byte[(int) file.length()];

        while (file.getFilePointer() != file.length()) {
            if (StringUtils.equals(file.readLine(), "-vm")) {
                String currentLine = file.readLine();
                if (StringUtils.equals(currentLine, javaHome)) {
                    logger.debug("JAVA_HOME and -vm in configuration file are same");
                } else {
                    logger.debug(
                            "JAVA_HOME and -vm in configuration file are different. Updating configuration file with JAVA_HOME");
                    file.seek(0);
                    file.readFully(text);
                    file.seek(0);
                    updateData(text, javaHome, currentLine, file);
                    isUpdated = true;
                }
                break;
            }
        }
    } catch (IOException ioException) {
        logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException);
    } finally {
        try {
            if (file != null) {
                file.close();
            }
        } catch (IOException ioException) {
            logger.error("IOException occurred while closing " + HYDROGRAPH_INI + " file", ioException);
        }
    }
    return isUpdated;
}

From source file:com.linkedin.helix.store.file.FilePropertyStore.java

@Override
public void updatePropertyUntilSucceed(String key, DataUpdater<T> updater, boolean createIfAbsent) {
    String path = getPath(key);/*from   ww w  .java2  s . c o m*/
    File file = new File(path);
    RandomAccessFile raFile = null;
    FileLock fLock = null;

    try {
        _readWriteLock.writeLock().lock();
        if (!file.exists()) {
            FileUtils.touch(file);
        }

        raFile = new RandomAccessFile(file, "rw");
        FileChannel fChannel = raFile.getChannel();
        fLock = fChannel.lock();

        T current = getProperty(key);
        T update = updater.update(current);
        setProperty(key, update);
    } catch (Exception e) {
        logger.error("fail to updatePropertyUntilSucceed, path:" + path, e);
    } finally {
        _readWriteLock.writeLock().unlock();
        try {
            if (fLock != null && fLock.isValid()) {
                fLock.release();
            }

            if (raFile != null) {
                raFile.close();
            }
        } catch (IOException e) {
            logger.error("fail to close file, path:" + path, e);
        }
    }
}

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   ww w.  j  a v a2 s.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!");
}

From source file:com.siblinks.ws.service.impl.CommentServiceImpl.java

/**
 * This method to get image from path directory Image question
 *
 * @param image//from  w  w  w . j a v a  2s  .c o m
 *            name
 *
 */
@Override
@RequestMapping(value = "/getImageQuestion/{name}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImageQuestion(@PathVariable(value = "name") final String name) {
    RandomAccessFile t = null;
    ResponseEntity<byte[]> responseEntity = null;
    try {
        if (name != null) {
            String directory = environment.getProperty("directoryImageQuestion");

            String path = directory + "/" + name + ".png";

            t = new RandomAccessFile(path, "r");
            byte[] r = new byte[(int) t.length()];
            t.readFully(r);
            responseEntity = new ResponseEntity<byte[]>(r, new HttpHeaders(), HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT);
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
    } finally {
        try {
            if (t != null) {
                t.close();
            }
        } catch (IOException e) {
            // do nothing
        }
    }
    return responseEntity;
}

From source file:com.guodong.sun.guodong.uitls.CacheUtil.java

/**
 * ? byte ?/*  w ww. j av  a2  s  .co  m*/
 *
 * @param key
 * @return byte ?
 */
public byte[] getAsBinary(String key) {
    RandomAccessFile raFile = null;
    boolean removeFile = false;
    try {
        File file = mCache.get(key);
        if (!file.exists())
            return null;
        raFile = new RandomAccessFile(file, "r");
        byte[] byteArray = new byte[(int) raFile.length()];
        raFile.read(byteArray);
        if (!Utils.isDue(byteArray)) {
            return Utils.clearDateInfo(byteArray);
        } else {
            removeFile = true;
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (raFile != null) {
            try {
                raFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (removeFile)
            remove(key);
    }
}

From source file:com.siblinks.ws.service.impl.CommentServiceImpl.java

/**
 * {@inheritDoc}/*from   w  w w .  ja va 2  s  .  c  o m*/
 */
@Override
@RequestMapping(value = "/getImageComment/{name}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImageComment(@PathVariable(value = "name") final String name) {
    ResponseEntity<byte[]> responseEntity = null;
    RandomAccessFile randomAccessFile = null;
    try {
        if (name != null) {
            String directory = environment.getProperty("directoryImageComment");
            String path = directory + "/" + name + ".png";

            randomAccessFile = new RandomAccessFile(path, "r");
            byte[] r = new byte[(int) randomAccessFile.length()];
            randomAccessFile.readFully(r);
            responseEntity = new ResponseEntity<byte[]>(r, new HttpHeaders(), HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT);
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
    } finally {
        try {
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
        } catch (IOException e) {
            // Do nothing
        }
    }
    return responseEntity;

}

From source file:com.sun.faban.harness.webclient.ResultAction.java

private String editResultInfo(String runID) throws FileNotFoundException, IOException {
    RunId runId = new RunId(runID);
    String ts = null;// w  w  w.  j  a v a 2s. c o m
    String[] status = new String[2];
    File file = new File(Config.OUT_DIR + runID + '/' + Config.RESULT_INFO);
    RandomAccessFile rf = new RandomAccessFile(file, "rwd");
    long size = rf.length();
    byte[] buffer = new byte[(int) size];
    rf.readFully(buffer);
    String content = new String(buffer, 0, (int) size);
    int idx = content.indexOf('\t');
    if (idx != -1) {
        status[0] = content.substring(0, idx).trim();
        status[1] = content.substring(++idx).trim();
    } else {
        status[0] = content.trim();
        int lastIdxln = status[0].lastIndexOf("\n");
        if (lastIdxln != -1)
            status[0] = status[0].substring(0, lastIdxln - 1);
    }
    if (status[1] != null) {
        ts = status[1];
    } else {
        String paramFileName = runId.getResultDir().getAbsolutePath() + File.separator + "run.xml";
        File paramFile = new File(paramFileName);
        long dt = paramFile.lastModified();
        ts = dateFormat.format(new Date(dt));
        rf.seek(rf.length());
        rf.writeBytes('\t' + ts.trim());
    }
    rf.close();
    return ts;
}

From source file:com.lewa.crazychapter11.MainActivity.java

private void WriteToSdCard(String content) {
    try {//from   ww  w.j  a v  a2s  .c  o  m
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sdCardDir = Environment.getExternalStorageDirectory();
            File targetFile = new File(sdCardDir.getCanonicalPath() + FILE_NAME_SDCARD);

            Log.i("crazyFile", "WriteToSdCard: sdCardDir=" + sdCardDir + " \n targetFile=" + targetFile);
            RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
            raf.seek(targetFile.length());
            raf.write(content.getBytes());
            raf.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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)
 */// w w w .  j  a  v a2 s . co  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);
}