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:com.linkedin.pinot.perf.ForwardIndexReaderBenchmark.java

public static void multiValuedReadBenchMarkV1(File file, int numDocs, int totalNumValues, int maxEntriesPerDoc,
        int columnSizeInBits) throws Exception {
    System.out.println("******************************************************************");
    System.out.println("Analyzing " + file.getName() + " numDocs:" + numDocs + ", totalNumValues:"
            + totalNumValues + ", maxEntriesPerDoc:" + maxEntriesPerDoc + ", numBits:" + columnSizeInBits);
    long start, end;
    boolean readFile = true;
    boolean randomRead = true;
    boolean contextualRead = true;
    boolean signed = false;
    boolean isMmap = false;
    PinotDataBuffer heapBuffer = PinotDataBuffer.fromFile(file, ReadMode.mmap, FileChannel.MapMode.READ_ONLY,
            "benchmarking");
    BaseSingleColumnMultiValueReader reader = new com.linkedin.pinot.core.io.reader.impl.v1.FixedBitMultiValueReader(
            heapBuffer, numDocs, totalNumValues, columnSizeInBits, signed);

    int[] intArray = new int[maxEntriesPerDoc];
    File outfile = new File("/tmp/" + file.getName() + ".raw");
    FileWriter fw = new FileWriter(outfile);
    for (int i = 0; i < numDocs; i++) {
        int length = reader.getIntArray(i, intArray);
        StringBuilder sb = new StringBuilder();
        String delim = "";
        for (int j = 0; j < length; j++) {
            sb.append(delim);//from  w w  w  .  j a v a2s.  co  m
            sb.append(intArray[j]);
            delim = ",";
        }
        fw.write(sb.toString());
        fw.write("\n");
    }
    fw.close();

    // sequential read
    if (readFile) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        ByteBuffer buffer = ByteBuffer.allocateDirect((int) file.length());
        raf.getChannel().read(buffer);
        for (int run = 0; run < MAX_RUNS; run++) {
            long length = file.length();
            start = System.currentTimeMillis();
            for (int i = 0; i < length; i++) {
                byte b = buffer.get(i);
            }
            end = System.currentTimeMillis();
            stats.addValue((end - start));
        }
        System.out.println("v1 multi value read bytes stats for " + file.getName());
        System.out.println(
                stats.toString().replaceAll("\n", ", ") + " raw:" + Arrays.toString(stats.getValues()));

        raf.close();
    }
    if (randomRead) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        for (int run = 0; run < MAX_RUNS; run++) {
            start = System.currentTimeMillis();
            for (int i = 0; i < numDocs; i++) {
                int length = reader.getIntArray(i, intArray);
            }
            end = System.currentTimeMillis();
            stats.addValue((end - start));
        }
        System.out.println("v1 multi value sequential read one stats for " + file.getName());
        System.out.println(
                stats.toString().replaceAll("\n", ", ") + " raw:" + Arrays.toString(stats.getValues()));
    }

    if (contextualRead) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        for (int run = 0; run < MAX_RUNS; run++) {
            MultiValueReaderContext context = (MultiValueReaderContext) reader.createContext();
            start = System.currentTimeMillis();
            for (int i = 0; i < numDocs; i++) {
                int length = reader.getIntArray(i, intArray, context);
            }
            end = System.currentTimeMillis();
            // System.out.println("RUN:" + run + "Time:" + (end-start));
            stats.addValue((end - start));
        }
        System.out.println("v1 multi value sequential read one with context stats for " + file.getName());
        System.out.println(
                stats.toString().replaceAll("\n", ", ") + " raw:" + Arrays.toString(stats.getValues()));

    }
    reader.close();
    heapBuffer.close();
    System.out.println("******************************************************************");

}

From source file:org.apache.jackrabbit.oak.segment.file.TarReader.java

/**
 * Collects all entries from the given file and optionally backs-up the
 * file, by renaming it to a ".bak" extension
 * //w ww .j  a v a 2s  .  c o m
 * @param file
 * @param entries
 * @param backup
 * @throws IOException
 */
private static void collectFileEntries(File file, LinkedHashMap<UUID, byte[]> entries, boolean backup)
        throws IOException {
    log.info("Recovering segments from tar file {}", file);
    try {
        RandomAccessFile access = new RandomAccessFile(file, "r");
        try {
            recoverEntries(file, access, entries);
        } finally {
            access.close();
        }
    } catch (IOException e) {
        log.warn("Could not read tar file {}, skipping...", file, e);
    }

    if (backup) {
        backupSafely(file);
    }
}

From source file:com.adaptris.core.fs.CompositeFileFilterTest.java

private void write(long size, File f) throws IOException {
    RandomAccessFile rf = new RandomAccessFile(f, "rw");
    rf.setLength(size);/*w  w w  .  j ava2  s.c o  m*/
    rf.close();
}

From source file:net.yacy.document.importer.MediawikiImporter.java

public static byte[] read(final File f, final long start, final int len) {
    final byte[] b = new byte[len];
    RandomAccessFile raf = null;
    try {/*w ww  . j a  va 2  s . c o m*/
        raf = new RandomAccessFile(f, "r");
        raf.seek(start);
        raf.read(b);
    } catch (final IOException e) {
        ConcurrentLog.logException(e);
        return null;
    } finally {
        if (raf != null)
            try {
                raf.close();
                try {
                    raf.getChannel().close();
                } catch (final IOException e) {
                }
            } catch (final IOException e) {
            }
    }
    return b;
}

From source file:com.adaptris.core.fs.enhanced.FileSorterCase.java

private void ensureSize(long size, File f) throws IOException {
    RandomAccessFile rf = new RandomAccessFile(f, "rw");
    rf.setLength(size);//from   ww  w  . j  a  v  a 2  s.  c o m
    rf.close();
}

From source file:Gen.java

public static void genWeb() throws Exception {

    String GEN_WEBINF = GEN_ROOT + FILE_SEPARATOR + "war" + FILE_SEPARATOR + "WEB-INF";

    String WAR_NAME = System.getProperty("warname") != null && !System.getProperty("warname").equals("")
            ? System.getProperty("warname")
            : MAPPING_JAR_NAME.substring(0, MAPPING_JAR_NAME.length() - "jar".length()) + "war";
    if (!WAR_NAME.endsWith(".war"))
        WAR_NAME += ".war";

    String PROPS_EMBED = System.getProperty("propsembed") != null
            && !System.getProperty("propsembed").equals("") ? System.getProperty("propsembed") : null;

    deleteDir(GEN_ROOT + FILE_SEPARATOR + "war");

    regenerateDir(GEN_WEBINF + FILE_SEPARATOR + "classes");
    regenerateDir(GEN_WEBINF + FILE_SEPARATOR + "lib");

    Vector<String> warJars = new Vector<String>();
    warJars.add(GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME);

    InputStream inputStreamCore = Gen.class.getResourceAsStream("/biocep-core-tomcat.jar");
    if (inputStreamCore != null) {
        try {//from  w  w  w  .  j  a  v  a2 s  .c o m
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(
                    GEN_WEBINF + FILE_SEPARATOR + "lib" + "/biocep-core.jar");
            int count = 0;
            while ((count = inputStreamCore.read(data, 0, BUFFER_SIZE)) != -1) {
                fos.write(data, 0, count);
            }
            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {

        warJars.add("RJB.jar");

        warJars.add("lib/desktop/JRI.jar");

        FilenameFilter jarsFilter = new FilenameFilter() {
            public boolean accept(File arg0, String arg1) {
                return arg1.endsWith(".jar");
            }
        };

        {
            String[] derby_jdbc_jars = new File("lib/jdbc").list(jarsFilter);
            for (int i = 0; i < derby_jdbc_jars.length; ++i) {
                warJars.add("lib/jdbc" + FILE_SEPARATOR + derby_jdbc_jars[i]);
            }
        }

        {
            String[] pool_jars = new File("lib/pool").list(jarsFilter);
            for (int i = 0; i < pool_jars.length; ++i) {
                warJars.add("lib/pool" + FILE_SEPARATOR + pool_jars[i]);
            }
        }

        {
            String[] httpclient_jars = new File("lib/j2ee").list(jarsFilter);
            for (int i = 0; i < httpclient_jars.length; ++i) {
                warJars.add("lib/j2ee" + FILE_SEPARATOR + httpclient_jars[i]);
            }
        }
    }

    log.info(warJars);
    for (int i = 0; i < warJars.size(); ++i) {
        Copy copyTask = new Copy();
        copyTask.setProject(_project);
        copyTask.setTaskName("copy to war");
        copyTask.setTodir(new File(GEN_WEBINF + FILE_SEPARATOR + "lib"));
        copyTask.setFile(new File(warJars.elementAt(i)));
        copyTask.init();
        copyTask.execute();
    }

    unzip(Gen.class.getResourceAsStream("/jaxws.zip"), GEN_WEBINF + FILE_SEPARATOR + "lib",
            new EqualNameFilter("activation.jar", "jaxb-api.jar", "jaxb-impl.jar", "jaxb-xjc.jar",
                    "jaxws-api.jar", "jaxws-libs.jar", "jaxws-rt.jar", "jaxws-tools.jar", "jsr173_api.jar",
                    "jsr181-api.jar", "jsr250-api.jar", "saaj-api.jar", "saaj-impl.jar", "sjsxp.jar",
                    "FastInfoset.jar", "http.jar", "mysql-connector-java-5.1.0-bin.jar", "ojdbc-14.jar"),
            BUFFER_SIZE, false, "Unzipping psTools..", 17);

    PrintWriter pw_web_xml = new PrintWriter(GEN_WEBINF + FILE_SEPARATOR + "web.xml");
    pw_web_xml.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    pw_web_xml.println(
            "<web-app version=\"2.4\" xmlns=\"http://java.sun.com/xml/ns/j2ee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\">");
    pw_web_xml.println(
            "<listener><listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class></listener>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_web_xml.println("<servlet><servlet-name>" + shortClassName
                + "_servlet</servlet-name><servlet-class>org.kchine.r.server.http.frontend.InterceptorServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");
    }

    pw_web_xml.println("<servlet><servlet-name>" + "WSServlet"
            + "</servlet-name><servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");

    pw_web_xml.println("<servlet><servlet-name>" + "MappingClassServlet"
            + "</servlet-name><servlet-class>org.kchine.r.server.http.frontend.MappingClassServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_web_xml.println(
                "<servlet-mapping><servlet-name>" + shortClassName + "_servlet</servlet-name><url-pattern>/"
                        + shortClassName + "</url-pattern></servlet-mapping>");
    }

    pw_web_xml.println("<servlet-mapping><servlet-name>" + "MappingClassServlet"
            + "</servlet-name><url-pattern>" + "/mapping/classes/*" + "</url-pattern></servlet-mapping>");

    pw_web_xml.println("<session-config><session-timeout>30</session-timeout></session-config>");
    pw_web_xml.println("</web-app>");
    pw_web_xml.flush();
    pw_web_xml.close();

    PrintWriter pw_sun_jaxws_xml = new PrintWriter(GEN_WEBINF + FILE_SEPARATOR + "sun-jaxws.xml");
    pw_sun_jaxws_xml.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    pw_sun_jaxws_xml.println("<endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime' version='2.0'>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_sun_jaxws_xml.println("   <endpoint    name='name_" + shortClassName + "'   implementation='"
                + className + "Web" + "' url-pattern='/" + shortClassName + "'/>");
    }

    pw_sun_jaxws_xml.println("</endpoints>");
    pw_sun_jaxws_xml.flush();
    pw_sun_jaxws_xml.close();

    if (PROPS_EMBED != null) {
        InputStream is = new FileInputStream(PROPS_EMBED);
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        RandomAccessFile raf = new RandomAccessFile(
                GEN_WEBINF + FILE_SEPARATOR + "classes" + FILE_SEPARATOR + "globals.properties", "rw");
        raf.setLength(0);
        raf.write(buffer);
        raf.close();
    }

    War warTask = new War();
    warTask.setProject(_project);
    warTask.setTaskName("war");
    warTask.setBasedir(new File(GEN_ROOT + FILE_SEPARATOR + "war"));
    warTask.setDestFile(new File(GEN_ROOT + FILE_SEPARATOR + WAR_NAME));
    warTask.setIncludes("**/*");
    warTask.init();
    warTask.execute();

}

From source file:eu.trentorise.smartcampus.feedback.test.TestFeedbackManagers.java

private void writeTestFile(byte[] data) throws IOException {
    RandomAccessFile f = new RandomAccessFile("src/test/resources/android_copy.jpg", "rw");
    f.write(data);/*from   w  w w  . j a  v a 2s  . c  o m*/
    f.close();
}

From source file:ch.cyberduck.core.io.FileBuffer.java

@Override
public synchronized void close() {
    this.length = 0L;
    if (temporary.exists()) {
        try {//from  www.ja  va2s .co  m
            final RandomAccessFile file = random();
            file.close();
        } catch (IOException e) {
            log.error(String.format("Failure closing buffer %s", this));
        } finally {
            try {
                temporary.delete();
                file = null;
            } catch (AccessDeniedException e) {
                log.warn(String.format(
                        "Failure removing temporary file %s for buffer %s. Schedule for delete on exit.",
                        temporary, this));
                Paths.get(temporary.getAbsolute()).toFile().deleteOnExit();
            }
        }
    }
}

From source file:ly.count.android.sdk.CrashDetails.java

private static long getTotalRAM() {
    if (totalMemory == 0) {
        RandomAccessFile reader = null;
        String load = null;//from w ww . ja  v a 2s  .  c o m
        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);
            }
            try {
                totalMemory = Long.parseLong(value) / 1024;
            } catch (NumberFormatException ex) {
                totalMemory = 0;
            }
        } catch (IOException ex) {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exc) {
                exc.printStackTrace();
            }
            ex.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exc) {
                exc.printStackTrace();
            }
        }
    }
    return totalMemory;
}

From source file:org.apache.servicecomb.demo.edge.business.Impl.java

protected File createBigFile() throws IOException {
    File file = new File(tempDir, "bigFile.txt");
    file.delete();//w  w  w .jav a2 s .  c o m
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
    randomAccessFile.setLength(10 * 1024 * 1024);
    randomAccessFile.close();
    return file;
}