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:edu.harvard.i2b2.patientMapping.serviceClient.IMQueryClient.java

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

    try {//  w ww .jav a  2s . c o  m
        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");
        PatientMappingFactory.append(f, "PatientNumber,Race,Sex,Age,Dead\n");
        PatientMappingFactory.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:eu.trentorise.smartcampus.feedback.test.TestFeedbackManagers.java

private byte[] readTestFile() throws IOException {
    RandomAccessFile f = new RandomAccessFile("src/test/resources/android.jpg", "r");
    byte[] b = new byte[(int) f.length()];
    f.read(b);/*  w ww  .j av  a  2s .  c  o  m*/
    f.close();
    return b;
}

From source file:org.commoncrawl.service.crawler.CrawlSegmentLog.java

public static void writeHeader(File logFilePath, int recordCount) throws IOException {
    RandomAccessFile stream = new RandomAccessFile(logFilePath, "rw");
    try {/*from w w  w  .ja va 2s  .  c  o m*/
        stream.seek(0);
        stream.writeInt(LogFileHeaderBytes);
        stream.writeInt(recordCount);
    } finally {
        // stream.getFD().sync();
        stream.close();
    }
}

From source file:net.iharding.utils.FileUtils.java

/**   
 * RandomAccessFile   /*  w  w w .j  a v a2s  . c o m*/
 *    
 * @param fileName ??   
 * @param content    
 */
public static void appendFile(String filePath, String content) {
    RandomAccessFile randomFile = null;
    try {
        // ???     
        randomFile = new RandomAccessFile(filePath, "rw");
        //      
        long fileLength = randomFile.length();
        //      
        randomFile.seek(fileLength);
        randomFile.writeUTF(content);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (randomFile != null) {
            try {
                randomFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:it.geosolutions.tools.io.file.Copy.java

/**
 * Copy the input file onto the output file using the specified buffer size.
 * //from   w  w  w.  ja  v  a2 s . c o  m
 * @param sourceFile
 *            the {@link File} to copy from.
 * @param destinationFile
 *            the {@link File} to copy to.
 * @param size
 *            buffer size.
 * @throws IOException
 *             in case something bad happens.
 */
public static void copyFile(File sourceFile, File destinationFile, int size) throws IOException {
    Objects.notNull(sourceFile, destinationFile);
    if (!sourceFile.exists() || !sourceFile.canRead() || !sourceFile.isFile())
        throw new IllegalStateException("Source is not in a legal state.");
    if (!destinationFile.exists()) {
        destinationFile.createNewFile();
    }
    if (destinationFile.getAbsolutePath().equalsIgnoreCase(sourceFile.getAbsolutePath()))
        throw new IllegalArgumentException("Cannot copy a file on itself");

    RandomAccessFile s = null, d = null;
    FileChannel source = null;
    FileChannel destination = null;
    try {
        s = new RandomAccessFile(sourceFile, "r");
        source = s.getChannel();
        d = new RandomAccessFile(destinationFile, "rw");
        destination = d.getChannel();
        IOUtils.copyFileChannel(size, source, destination);
    } finally {
        if (source != null) {
            try {
                source.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }
        if (s != null) {
            try {
                s.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }

        if (destination != null) {
            try {
                destination.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }

        if (d != null) {
            try {
                d.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }
    }
}

From source file:edu.harvard.i2b2.analysis.dataModel.TimelineFactory.java

public static String generateTimelineData(String result, ArrayList<TimelineRow> rows, boolean writeFile,
        boolean displayAll, boolean displayDemographics) {

    try {//from www.  ja  v  a 2  s  . c  o m
        PDOResponseMessageModel pdoresponsefactory = new PDOResponseMessageModel();
        StatusType statusType = pdoresponsefactory.getStatusFromResponseXML(result);
        if (!statusType.getType().equalsIgnoreCase("DONE")) {
            return "error";
        }

        StringBuilder resultFile = new StringBuilder();
        resultFile.append(GetTimelineHeader());

        PatientSet patientDimensionSet = pdoresponsefactory.getPatientSetFromResponseXML(result);
        if (patientDimensionSet != null) {
            log.debug("Total patient: " + patientDimensionSet.getPatient().size());
            // for(int i=0;
            // i<patientDimensionSet.getPatientDimension().size();i++) {
            // PatientDimensionType patientType =
            // patientDimensionSet.getPatientDimension().get(i);
            // System.out.println("PatientNum: " +
            // patientType.getPatientNum());
            // }
        } else {
            return "error";
        }

        // / testing the visit set
        // PatientDataType.VisitDimensionSet visitSet =
        // pdoresponsefactory.getVisitSetFromResponseXML(result);
        // System.out.println("Total visits: "+visitSet.getVisitDimension().
        // size());

        List<ObservationSet> factSets = pdoresponsefactory.getFactSetsFromResponseXML(result);

        log.debug("\nGenerate lld:");
        for (int i = 0; i < patientDimensionSet.getPatient().size(); i++) {
            PatientType patientType = patientDimensionSet.getPatient().get(i);
            String pnum = patientType.getPatientId().getValue();
            // Integer pnum = new Integer(snum);
            // log.debug("PatientNum: " + snum);

            if (displayDemographics) {
                resultFile.append(getTimelinePatientString(pnum.toString(), patientType));
            } else {
                resultFile.append(getTimelinePatientString(pnum.toString()));
            }

            String path = null;
            TimelineRow currentRow = null;
            ObservationSet observationFactSet = null;

            for (int j = 0; j < rows.size(); j++) {
                TimelineRow row = rows.get(j);
                int total = 0;
                StringBuilder resultString = new StringBuilder();

                // loop thru all the pdo sets for this row here
                for (int s = 0; s < row.pdoItems.size(); s++) {
                    PDOItem pset = row.pdoItems.get(s);
                    observationFactSet = null;

                    for (int m = 0; m < factSets.size(); m++) {
                        ObservationSet tmpFactSet = factSets.get(m);
                        if (tmpFactSet.getPanelName().equalsIgnoreCase(pset.fullPath)) {
                            observationFactSet = tmpFactSet;
                            path = observationFactSet.getPanelName();
                            currentRow = row;
                            break;
                        }
                    }

                    if (observationFactSet == null) {
                        continue;
                    }

                    XMLGregorianCalendar curStartDate = null;
                    for (int k = 0; k < observationFactSet.getObservation().size(); k++) {
                        ObservationType obsFactType = observationFactSet.getObservation().get(k);

                        if (pnum.equals(obsFactType.getPatientId().getValue())) {
                            /*   if ((curStartDate != null)
                                     && (obsFactType.getStartDate().compare(
                            curStartDate) == DatatypeConstants.EQUAL)) {
                                  continue;
                               }
                               */

                            String sStart_date = obsFactType.getStartDate().getMonth() + "-"
                                    + obsFactType.getStartDate().getDay() + "-"
                                    + obsFactType.getStartDate().getYear() + " 12:00";
                            String sEnd_date;
                            if (obsFactType.getEndDate() == null) {
                                sEnd_date = sStart_date;
                            } else {
                                sEnd_date = obsFactType.getEndDate().getMonth() + "-"
                                        + obsFactType.getEndDate().getDay() + "-"
                                        + obsFactType.getEndDate().getYear() + " 12:00";
                            }

                            double nval = -1;
                            if (obsFactType.getNvalNum().getValue() != null) {
                                nval = obsFactType.getNvalNum().getValue().doubleValue();
                            }
                            PDOValueData valdp = null;

                            if (pset.hasValueDisplayProperty) {
                                for (int n = 0; n < pset.valDisplayProperties.size(); n++) {
                                    PDOValueData tmpvaldp = pset.valDisplayProperties.get(n);
                                    // if (tmpvaldp.inRange(nval)) {
                                    valdp = tmpvaldp;
                                    // break;
                                    // }
                                }

                                String sValue = getSValue(row.displayName, obsFactType, true);
                                if ((curStartDate != null) && (obsFactType.getStartDate()
                                        .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                    resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                            "slateblue", valdp.height, sValue));
                                } else {
                                    resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                            valdp.color, valdp.height, sValue));
                                }
                            } else {
                                String sValue = getSValue(row.displayName, obsFactType, false);
                                if ((curStartDate != null) && (obsFactType.getStartDate()
                                        .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                    resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                            "slateblue", pset.height, sValue));
                                } else {
                                    resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                            pset.color, pset.height, sValue));
                                }
                            }

                            total++;
                            curStartDate = obsFactType.getStartDate();
                        }
                    }
                }

                if (total > 0) {
                    // log.debug("-- "+path+" has "+total+" events");
                    resultFile.append(getTimelineConceptString(row.displayName, total));

                    // log.debug(resultString.toString());
                    resultFile.append(resultString);
                } else {
                    // display all
                    if (displayAll) {
                        // log.debug("-- "+path+" has "+total+" events");
                        resultFile.append(getTimelineConceptString(row.displayName, 1));

                        // log.debug(getTimelineEmptyDateString());
                        resultFile.append(getTimelineEmptyDateString());
                    }
                }
            }
        }

        resultFile.append(GetTimelineFooter());

        if (writeFile) {
            String i2b2File = System.getProperty("user.dir") + "/temp/" + "i2b2xml.lld";
            File oDelete = new File(i2b2File);
            if (oDelete != null)
                oDelete.delete();
            RandomAccessFile f = new RandomAccessFile(i2b2File, "rw");
            append(f, resultFile.toString());
            f.close();
        }

        // log.debug("\nThe lld file: \n"+resultFile.toString());
        return resultFile.toString();
    } catch (org.apache.axis2.AxisFault e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return null;
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return "error";
    }
}

From source file:hoot.services.info.ErrorLog.java

public String generateExportLog() throws Exception {
    String fileId = UUID.randomUUID().toString();
    String outputPath = _tempOutputPath + "/" + fileId;

    String data = "";

    AboutResource about = new AboutResource();
    VersionInfo vInfo = about.getCoreVersionInfo();
    data = "\n************ CORE VERSION INFO ***********\n";
    data += vInfo.toString();//from  ww  w . j  a va2 s. c  om
    CoreDetail cd = about.getCoreVersionDetail();
    data += "\n************ CORE ENVIRONMENT ***********\n";
    if (cd != null) {
        data += StringUtils.join(cd.getEnvironmentInfo(), '\n');
    }

    data = "\n************ SERVICE VERSION INFO ***********\n";
    data += about.getServicesVersionInfo().toString();
    ServicesDetail sd = about.getServicesVersionDetail();
    if (sd != null) {
        data += "\n************ SERVICE DETAIL PROPERTY ***********\n";
        for (ServicesDetail.Property prop : sd.getProperties()) {
            String str = prop.getName() + " : " + prop.getValue() + "\n";
            data += str;
        }

        data += "\n************ SERVICE DETAIL RESOURCE ***********\n";
        for (ServicesDetail.ServicesResource res : sd.getResources()) {
            String str = res.getType() + " : " + res.getUrl() + "\n";
            data += str;
        }
    }

    data += "\n************ CATALINA LOG ***********\n";

    // 5MB Max
    int maxSize = 5000000;

    String logStr = getErrorlog(maxSize);

    RandomAccessFile raf = new RandomAccessFile(outputPath, "rw");
    raf.writeBytes(data + "\n" + logStr);
    raf.close();
    return outputPath;
}

From source file:com.btoddb.fastpersitentqueue.MemorySegmentSerializer.java

public void saveToDisk(MemorySegment segment) throws IOException {
    File theFile = createPagingFile(segment);
    RandomAccessFile raFile = new RandomAccessFile(theFile, "rw");
    try {/*from  ww  w  .  ja v a2 s  .  co m*/
        segment.writeToDisk(raFile);
    } finally {
        raFile.close();
    }
}

From source file:com.btoddb.fastpersitentqueue.MemorySegmentSerializer.java

public void loadFromDisk(File theFile, MemorySegment segment) throws IOException {
    RandomAccessFile raFile = new RandomAccessFile(theFile, "r");
    try {/*www .  ja  v  a  2  s  .c o  m*/
        segment.readFromPagingFile(raFile);
    } finally {
        raFile.close();
    }
}

From source file:com.github.nlloyd.hornofmongo.MongoScope.java

public static Object fuzzFile(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    if (args.length != 2)
        Context.throwAsScriptRuntimeEx(new MongoScriptException("fuzzFile takes 2 arguments"));
    File fileToFuzz;/*  w w  w.j a  v a 2 s .  c  o m*/
    try {
        fileToFuzz = resolveFilePath((MongoScope) thisObj, Context.toString(args[0])).getCanonicalFile();
    } catch (IOException e) {
        Context.throwAsScriptRuntimeEx(new MongoScriptException(e));
        return null;
    }
    RandomAccessFile fuzzFile = null;
    try {
        fuzzFile = new RandomAccessFile(fileToFuzz, "rw");
        long fuzzPosition = Double.valueOf(Context.toNumber(args[1])).longValue();
        fuzzFile.seek(fuzzPosition);
        int byteToFuzz = fuzzFile.readByte();
        byteToFuzz = ~byteToFuzz;
        fuzzFile.seek(fuzzPosition);
        fuzzFile.write(byteToFuzz);
        fuzzFile.close();
    } catch (FileNotFoundException e) {
        Context.throwAsScriptRuntimeEx(e);
    } catch (IOException e) {
        Context.throwAsScriptRuntimeEx(e);
    } finally {
        if (fuzzFile != null) {
            try {
                fuzzFile.close();
            } catch (IOException e) {
            }
        }
    }

    return Undefined.instance;
}