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.bigdata.dastor.io.SSTableReader.java

private static MappedByteBuffer mmap(String filename, long start, int size) throws IOException {
    RandomAccessFile raf;
    try {/*from   w w w. j  a va2s.com*/
        raf = new RandomAccessFile(filename, "r");
    } catch (FileNotFoundException e) {
        throw new IOError(e);
    }

    try {
        return raf.getChannel().map(FileChannel.MapMode.READ_ONLY, start, size);
    } finally {
        raf.close();
    }
}

From source file:edu.harvard.i2b2.analysis.queryClient.CRCQueryClient.java

private static void testWriteTableFile(String result) {
    StringBuilder resultFile = new StringBuilder();

    try {//from w  ww  .j a v  a 2 s .c  om
        PDOResponseMessageModel pdoresponsefactory = new PDOResponseMessageModel();
        PatientSet patientDimensionSet = pdoresponsefactory.getPatientSetFromResponseXML(result);
        if (patientDimensionSet != null) {
            log.debug("Total patient: " + patientDimensionSet.getPatient().size());
            for (int i = 0; i < patientDimensionSet.getPatient().size(); i++) {
                PatientType patientType = patientDimensionSet.getPatient().get(i);
                log.debug("PatientNum: " + patientType.getPatientId());
                // + ","+patientType.getRaceCd()
                // +","+patientType.getSexCd()
                // +","+patientType.getAgeInYearsNum()
                // +","+patientType.getVitalStatusCd());
                resultFile.append(patientType.getPatientId());
                // +","+patientType.getRaceCd()
                // +","+patientType.getSexCd()
                // +","+patientType.getAgeInYearsNum()
                // +","+patientType.getVitalStatusCd()+"\n");
            }
        }

        /*
         * List<PatientDataType.ObservationFactSet> factSets =
         * pdoresponsefactory.getFactSetsFromResponseXML(result);
         * 
         * for(int j=0; j<factSets.size(); j++) {
         * PatientDataType.ObservationFactSet observationFactSet =
         * factSets.get(j);
         * //pdoresponsefactory.getFactSetFromResponseXML(result); if
         * (observationFactSet != null) {
         * log.debug("Total fact: "+observationFactSet
         * .getObservationFact().size()
         * +" for "+observationFactSet.getPath()
         * +"-"+observationFactSet.getConceptName()); for(int i=0;
         * i<observationFactSet.getObservationFact().size(); i++) {
         * ObservationFactType obsFactType =
         * observationFactSet.getObservationFact().get(i);
         * log.debug("PatientNum: "+obsFactType.getPatientNum()
         * +" concept_cd: " + obsFactType.getConceptCd() +" start_date: " +
         * obsFactType.getStartDate().getYear()
         * +"_"+obsFactType.getStartDate().getMonth()
         * +"_"+obsFactType.getStartDate().getDay()
         * +"_"+obsFactType.getNvalNum() +"_"+obsFactType.getConceptCd()
         * +"_"+obsFactType.getPatientNum()); } } }
         */

        String tableFile = "C:\\tableview\\data\\patienttable.txt";
        File oDelete = new File(tableFile);
        if (oDelete != null)
            oDelete.delete();
        RandomAccessFile f = new RandomAccessFile(tableFile, "rw");
        TimelineFactory.append(f, "PatientNumber,Race,Sex,Age,Dead\n");
        TimelineFactory.append(f, resultFile.toString());
        f.close();

        /*
         * log.debug("\nTesting lld:"); for(int i=0;
         * i<patientDimensionSet.getPatientDimension().size();i++) {
         * PatientDimensionType patientType =
         * patientDimensionSet.getPatientDimension().get(i); Integer pnum =
         * patientType.getPatientNum(); log.debug("PatientNum: " +
         * patientType.getPatientNum());
         * 
         * for(int j=0; j<factSets.size(); j++) {
         * PatientDataType.ObservationFactSet observationFactSet =
         * factSets.get(j); String path = observationFactSet.getPath();
         * StringBuilder resultString = new StringBuilder(); int total = 0;
         * XMLGregorianCalendar curStartDate = null; for(int k=0;
         * k<observationFactSet.getObservationFact().size(); k++) {
         * ObservationFactType obsFactType =
         * observationFactSet.getObservationFact().get(k);
         * 
         * if(pnum.intValue() == obsFactType.getPatientNum().intValue()) {
         * if((curStartDate != null) &&
         * (obsFactType.getStartDate().compare(curStartDate) ==
         * DatatypeConstants.EQUAL)) { continue; }
         * 
         * resultString.append("PatientNum: "+obsFactType.getPatientNum()
         * //+" for "+path +" concept_cd: " + obsFactType.getConceptCd()
         * +" start_date: " + obsFactType.getStartDate().getYear()
         * +"_"+obsFactType.getStartDate().getMonth()
         * +"_"+obsFactType.getStartDate().getDay()
         * +"_"+obsFactType.getStartDate().getHour()
         * +":"+obsFactType.getStartDate().getMinute()
         * +"_"+obsFactType.getNvalNum() +"_"+obsFactType.getConceptCd()
         * +"_"+obsFactType.getPatientNum()
         * +"_"+obsFactType.getEndDate()+"\n"); total++; curStartDate =
         * obsFactType.getStartDate(); } }
         * 
         * log.debug("-- "+path+" has "+total+" events");
         * log.debug(resultString.toString()); } }
         */
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ValidateLicenseHeaders.java

/**
 * Replace a legacy jboss header with the current default header
 * //w  w w.  j  a  v a  2s  .c  o  m
 * @param javaFile -
 *          the java source file
 * @param endOfHeader -
 *          the offset to the end of the legacy header
 * @throws IOException -
 *           thrown on failure to replace the header
 */
static void replaceHeader(File javaFile, long endOfHeader) throws IOException {
    if (log.isLoggable(Level.FINE))
        log.fine("Replacing legacy jboss header in: " + javaFile);
    RandomAccessFile raf = new RandomAccessFile(javaFile, "rw");
    File bakFile = new File(javaFile.getAbsolutePath() + ".bak");
    FileOutputStream fos = new FileOutputStream(bakFile);
    fos.write(DEFAULT_HEADER.getBytes());
    FileChannel fc = raf.getChannel();
    long count = raf.length() - endOfHeader;
    fc.transferTo(endOfHeader, count, fos.getChannel());
    fc.close();
    fos.close();
    raf.close();
    if (javaFile.delete() == false)
        log.severe("Failed to delete java file: " + javaFile);
    if (bakFile.renameTo(javaFile) == false)
        throw new SyncFailedException("Failed to replace: " + javaFile);
}

From source file:se.bitcraze.crazyflielib.bootloader.Bootloader.java

public static byte[] readFile(File file) throws IOException {
    byte[] fileData = new byte[(int) file.length()];
    Logger logger = LoggerFactory.getLogger("Bootloader");
    logger.debug("readFile: " + file.getName() + ", size: " + file.length());
    RandomAccessFile raf = null;
    try {//from  w w  w . j a  v a  2 s  .co  m
        raf = new RandomAccessFile(file.getAbsoluteFile(), "r");
        raf.readFully(fileData);
    } finally {
        if (raf != null) {
            try {
                raf.close();
            } catch (IOException ioe) {
                logger.error(ioe.getMessage());
            }
        }
    }
    return fileData;
}

From source file:com.aliyun.oss.integrationtests.TestUtils.java

public static String genFixedLengthFile(long fixedLength) throws IOException {
    ensureDirExist(TestBase.UPLOAD_DIR);
    String filePath = TestBase.UPLOAD_DIR + System.currentTimeMillis();
    RandomAccessFile raf = new RandomAccessFile(filePath, "rw");
    FileChannel fc = raf.getChannel();

    MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, fixedLength);
    try {/*from  ww w .j  a  va2  s .c  o m*/
        for (int i = 0; i < fixedLength; i++) {
            mbb.put(pickupAlphabet());
        }
        return filePath;
    } finally {
        if (fc != null) {
            fc.close();
        }

        if (raf != null) {
            raf.close();
        }
    }
}

From source file:count.ly.messaging.CrashDetails.java

private static long getTotalRAM() {
    if (totalMemory == 0) {
        RandomAccessFile reader = null;
        String load = null;/*from  ww  w  .  j  a v  a  2  s.  co 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);
            }
            reader.close();

            totalMemory = Long.parseLong(value) / 1024;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return totalMemory;
}

From source file:in.bbat.license.LicenseManager.java

public static void cleanupOlderLicenseFiles() {
    File localFile1 = new File("");
    File[] arrayOfFile1 = localFile1.listFiles(new FilenameFilter() {
        public boolean accept(File paramAnonymousFile, String paramAnonymousString) {
            return paramAnonymousString.endsWith(".license.lock");
        }//w  w w .j  a v  a 2 s  . co m
    });
    for (File localFile2 : arrayOfFile1) {
        FileLock localFileLock = null;
        RandomAccessFile localRandomAccessFile = null;
        try {
            localRandomAccessFile = new RandomAccessFile(localFile2, "rw");
            localFileLock = localRandomAccessFile.getChannel().tryLock();
        } catch (Exception localException) {
            localFileLock = null;
        }
        if (localFileLock != null) {
            try {
                localFileLock.release();
                localRandomAccessFile.close();
            } catch (IOException localIOException1) {
                LOG.error("Error releasing an acquired lock. No problem, continuing!");
            }
            String str = null;
            try {
                str = FileUtils.readFileToString(localFile2);
                returnOlderLicense(str);
                localFile2.delete();
            } catch (IOException localIOException2) {
                LOG.error("Error returning an older license that is no longer valid. No problem, continuing!");
            }
        }
    }
}

From source file:com.aliyun.oss.integrationtests.TestUtils.java

public static String genRandomLengthFile() throws IOException {
    ensureDirExist(TestBase.UPLOAD_DIR);
    String filePath = TestBase.UPLOAD_DIR + System.currentTimeMillis();
    RandomAccessFile raf = new RandomAccessFile(filePath, "rw");
    FileChannel fc = raf.getChannel();

    long fileLength = rand.nextInt(MAX_RANDOM_LENGTH);
    MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, fileLength);
    try {//w w w.  j  a v a2 s . c  o  m
        for (int i = 0; i < fileLength; i++) {
            mbb.put(pickupAlphabet());
        }
        return filePath;
    } finally {
        if (fc != null) {
            fc.close();
        }

        if (raf != null) {
            raf.close();
        }
    }
}

From source file:dk.netarkivet.common.utils.cdx.BinSearch.java

/** Given a file in sorted order and a prefix to search for, return a
 * an iterable that will return the lines in the files that start with
 * the prefix, in order.  They will be read lazily from the file.
 *
 * If no matches are found, it will still return an iterable with no
 * entries.//  www .ja  va 2s .  co  m
 *
 * @param file A CDX file to search in.
 * @param prefix The line prefix to search for.
 * @return An Iterable object that will return the lines
 * matching the prefix in the file.
 */
public static Iterable<String> getLinesInFile(File file, String prefix) {
    try {
        RandomAccessFile in = null;
        try {
            in = new RandomAccessFile(file, "r");
            long matchingline = binSearch(in, prefix);
            if (matchingline == -1) {
                // Simple empty Iterable
                return Collections.emptyList();
            }
            long firstMatching = findFirstLine(in, prefix, matchingline);
            return new PrefixIterable(file, firstMatching, prefix);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    } catch (IOException e) {
        String message = "IOException reading file '" + file + "'";
        log.warn(message, e);
        throw new IOFailure(message, e);
    }
}

From source file:de.ailis.wlandsuite.htds.Htds.java

/**
 * Returns the offsets of the tileset MSQ blocks in the specified file.
 * The offsets are determined by reading the raw data of each block and
 * looking at the position in the file./*  w w  w  .java2s.  co m*/
 *
 * @param file
 *            The file
 * @return The offsets
 * @throws IOException
 *             When file operation fails.
 */

public static List<Integer> getMsqOffsets(final File file) throws IOException {
    List<Integer> offsets;
    RandomAccessFile access;
    FileInputStream stream;
    MsqHeader header;
    long offset;
    byte[] dummy;
    HuffmanInputStream huffmanStream;

    offsets = new ArrayList<Integer>();
    access = new RandomAccessFile(file, "r");
    try {
        stream = new FileInputStream(access.getFD());
        offset = 0;
        while ((header = MsqHeader.read(stream)) != null) {
            offsets.add(Integer.valueOf((int) offset));
            huffmanStream = new HuffmanInputStream(stream);
            dummy = new byte[header.getSize()];
            huffmanStream.read(dummy);
            offset = access.getFilePointer();
        }
    } finally {
        access.close();
    }
    return offsets;
}