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:be.roots.taconic.pricingguide.util.iTextUtil.java

public static byte[] embedFont(byte[] pdf, String fontFileName, String fontName)
        throws IOException, DocumentException {

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        // the font file
        RandomAccessFile raf = new RandomAccessFile(fontFileName, "r");
        byte fontfile[] = new byte[(int) raf.length()];
        raf.readFully(fontfile);/* ww  w  . j  av a  2 s.c om*/
        raf.close();
        // create a new stream for the font file
        PdfStream stream = new PdfStream(fontfile);
        stream.flateCompress();
        stream.put(PdfName.LENGTH1, new PdfNumber(fontfile.length));
        // create a reader object
        PdfReader reader = new PdfReader(pdf);
        int n = reader.getXrefSize();
        PdfObject object;
        PdfDictionary font;
        PdfStamper stamper = new PdfStamper(reader, baos);
        PdfName fontname = new PdfName(fontName);
        for (int i = 0; i < n; i++) {
            object = reader.getPdfObject(i);
            if (object == null || !object.isDictionary())
                continue;
            font = (PdfDictionary) object;
            if (PdfName.FONTDESCRIPTOR.equals(font.get(PdfName.TYPE1))
                    && fontname.equals(font.get(PdfName.FONTNAME))) {
                PdfIndirectObject objref = stamper.getWriter().addToBody(stream);
                font.put(PdfName.FONTFILE2, objref.getIndirectReference());
            }
        }
        stamper.close();
        reader.close();
        return baos.toByteArray();
    }
}

From source file:net.yacy.document.parser.tarParser.java

public final static boolean isTar(File f) {
    if (!f.exists() || f.length() < 0x105)
        return false;
    RandomAccessFile raf = null;
    try {//w  w  w.  ja va2  s .c  o m
        raf = new RandomAccessFile(f, "r");
        raf.seek(0x101);
        byte[] b = new byte[5];
        raf.read(b);
        return MAGIC.equals(UTF8.String(b));
    } catch (final FileNotFoundException e) {
        return false;
    } catch (final IOException e) {
        return false;
    } finally {
        if (raf != null)
            try {
                raf.close();
            } catch (final IOException e) {
            }
    }
}

From source file:com.github.neoio.nio.util.NIOUtils.java

public static FileLock tryLock(File file) {
    FileLock toReturn = null;//from   w  ww.  j  a v a 2  s . c  o m

    try {
        RandomAccessFile raf = new RandomAccessFile(file, "rw");

        try {
            FileChannel channel = raf.getChannel();
            toReturn = channel.tryLock();
            raf.writeBytes("lock file for: " + ManagementFactory.getRuntimeMXBean().getName());
        } finally {
            if (toReturn == null)
                raf.close();
        }
    } catch (OverlappingFileLockException e) {
        toReturn = null;
    } catch (FileNotFoundException e) {
        toReturn = null;
    } catch (IOException e) {
        toReturn = null;
    }

    return toReturn;
}

From source file:org.apache.jackrabbit.core.data.FileDataStore.java

/**
 * Set the last modified date of a file, if the file is writable.
 *
 * @param file the file/*from ww w  . ja v  a  2 s. c o m*/
 * @param time the new last modified date
 * @throws DataStoreException if the file is writable but modifying the date fails
 */
private static void setLastModified(File file, long time) throws DataStoreException {
    if (!file.setLastModified(time)) {
        if (!file.canWrite()) {
            // if we can't write to the file, so garbage collection will also not delete it
            // (read only files or file systems)
            return;
        }
        try {
            // workaround for Windows: if the file is already open for reading
            // (in this or another process), then setting the last modified date
            // doesn't work - see also JCR-2872
            RandomAccessFile r = new RandomAccessFile(file, "rw");
            try {
                r.setLength(r.length());
            } finally {
                r.close();
            }
        } catch (IOException e) {
            throw new DataStoreException("An IO Exception occurred while trying to set the last modified date: "
                    + file.getAbsolutePath(), e);
        }
    }
}

From source file:Main.java

public static float getTotalRAM() {
    RandomAccessFile reader = null;
    String load = null;// w  ww  .j  a  v  a 2s  . c  o m
    DecimalFormat twoDecimalForm = new DecimalFormat("#.##");
    double totRam = 0;
    float lastValue = 0;
    try {
        reader = new RandomAccessFile("/proc/meminfo", "r");
        load = reader.readLine();

        // Get the Number value from the string
        Pattern p = Pattern.compile("(\\d+)");
        Matcher m = p.matcher(load);
        String value = "";
        while (m.find()) {
            value = m.group(1);
            // System.out.println("Ram : " + value);
        }
        reader.close();

        totRam = Double.parseDouble(value);
        // totRam = totRam / 1024;

        float mb = (float) (totRam / 1024.0f);
        float gb = (float) (totRam / 1048576.0f);
        float tb = (float) (totRam / 1073741824.0f);

        lastValue = gb;
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        // Streams.close(reader);
    }

    return lastValue;
}

From source file:com.shopgun.android.sdk.utils.ExternalClientIdStore.java

public static String getCid(ShopGun sgn) {

    // First try SharedPrefs
    String cid = sgn.getSettings().getClientId();
    if (cid != null) {
        return cid;
    }/*ww w.j a v a  2s  .  co  m*/

    // Then try external storage
    File cidFile = getCidFile(sgn.getContext());
    if (cidFile == null) {
        return null;
    }

    RandomAccessFile f = null;
    try {
        f = new RandomAccessFile(cidFile, "r");
        // Get and check length
        long longlength = f.length();
        int length = (int) longlength;
        if (length != longlength)
            return null;
        // Read file and return data
        byte[] data = new byte[length];
        f.readFully(data);
        return new String(data);
    } catch (Exception e) {
        // Ignore
    } finally {
        try {
            f.close();
        } catch (Exception e) {
            // Ignore
        }

        // Cleanup the cid file, we won't need it any more
        deleteCidFile(sgn.getContext());
    }

    return null;
}

From source file:Main.java

public static double getCpuUsage1() {
    try {//from w  ww.  ja va2s  .  c  o  m
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();
        String[] toks = load.split(" ");

        double user1 = Double.parseDouble(toks[2]);
        double system1 = Double.parseDouble(toks[4]);
        double irq1 = Double.parseDouble(toks[7]);
        double idle1 = Double.parseDouble(toks[5]);
        try {
            Thread.sleep(360);
        } catch (Exception e) {
            e.printStackTrace();
        }
        reader.seek(0);
        load = reader.readLine();
        reader.close();
        toks = load.split(" ");
        double user2 = Double.parseDouble(toks[2]);
        double system2 = Double.parseDouble(toks[4]);
        double irq2 = Double.parseDouble(toks[7]);
        double idle2 = Double.parseDouble(toks[5]);

        double user_pass = user2 - user1;
        double system_pass = system2 - system1;
        double irq_pass = irq2 - irq1;
        double idle_pass = idle2 - idle1;
        double usage = (user_pass + system_pass + irq_pass) * 100.00
                / (user_pass + irq_pass + system_pass + idle_pass);
        BigDecimal b = new BigDecimal(usage);
        double res = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return res;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    return 0;

}

From source file:org.apache.hadoop.dfs.TestDatanodeBlockScanner.java

public static boolean corruptReplica(String blockName, int replica) throws IOException {
    Random random = new Random();
    File baseDir = new File(System.getProperty("test.build.data"), "dfs/data");
    boolean corrupted = false;
    for (int i = replica * 2; i < replica * 2 + 2; i++) {
        File blockFile = new File(baseDir, "data" + (i + 1) + "/current/" + blockName);
        if (blockFile.exists()) {
            // Corrupt replica by writing random bytes into replica
            RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
            FileChannel channel = raFile.getChannel();
            String badString = "BADBAD";
            int rand = random.nextInt((int) channel.size() / 2);
            raFile.seek(rand);/* w  ww  .j ava2 s .c  om*/
            raFile.write(badString.getBytes());
            raFile.close();
            corrupted = true;
        }
    }
    return corrupted;
}

From source file:com.github.hexocraft.worldrestorer.WorldRestorerApi.java

private static boolean isCompletelyWritten(File file) {
    RandomAccessFile stream = null;
    try {/*from ww w .  j  a  v  a2  s  .co  m*/
        stream = new RandomAccessFile(file, "rw");
    } catch (Exception e) {
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
            }
            return true;
        }
    }
    return false;
}

From source file:com.feilong.tools.net.ZClientTest.java

/**
 * Gets the files./*  ww  w .  j ava2s  .co  m*/
 * 
 * @param ftp
 *            the ftp
 * @param localDir
 *            the local dir
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static void testGetFiles(FTPClient ftp, File localDir) throws IOException {
    String[] names = ftp.listNames();
    for (String name : names) {
        File file = new File(localDir.getPath() + File.separator + name);
        if (!file.exists()) {
            file.createNewFile();
        }
        long pos = file.length();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.seek(pos);
        ftp.setRestartOffset(pos);
        InputStream is = ftp.retrieveFileStream(name);
        if (is == null) {
            log.info("no such file:" + name);
        } else {
            log.info("start getting file:" + name);
            int b;
            while ((b = is.read()) != -1) {
                raf.write(b);
            }
            is.close();
            if (ftp.completePendingCommand()) {
                log.info("done!");
            } else {
                log.info("can't get file:" + name);
            }
        }
        raf.close();
    }
}