List of usage examples for java.io RandomAccessFile close
public void close() throws IOException
From source file:net.sf.zekr.common.resource.QuranText.java
/** * The private constructor, which loads the whole Quran text from file into memory (<code>quranText</code> * ).//w w w . j a v a2 s .c o m * * @param textType can be either UTHMANI_MODE or SIMPLE_MODE * @throws IOException */ protected QuranText(int textType) throws IOException { mode = textType; String qFile = ApplicationPath.SIMPLE_QURAN_TEXT_FILE; if (textType == UTHMANI_MODE) { qFile = ApplicationPath.UTHMANI_QURAN_TEXT_FILE; } RandomAccessFile raf = new RandomAccessFile(qFile, "r"); byte[] buf = new byte[(int) raf.length()]; raf.readFully(buf); rawText = new String(buf, config.getProps().getString("quran.text.encoding")); refineRawText(); raf.close(); }
From source file:edu.harvard.i2b2.analysis.dataModel.TimelineFactory.java
public static String createlld(int minPatientNum, int maxPatientNum, boolean bDisplayAll, boolean writeFile, boolean displayDemographics) { ArrayList conceptOrder = new ArrayList(); int maxLineCount = 0; // zero turns off check for maximum count of lines StringBuilder resultFile = new StringBuilder(); ArrayList<PatientDemographics> demographicsArray = new ArrayList<PatientDemographics>(); try {// w w w. ja va 2s . c o m // get the root Element root = null;// doc.getRootElement(); // get the children from the i2b2 document java.util.List allChildren = root.getChildren(); int iNumberOfChildren = allChildren.size(); // set up the variables for the loop String sPatient_num = null; String sConcept_cd = null; String sOldPatient_num = "start"; String sOldConcept_cd = null; String sStart_date = null; String sOldStart_date = null; String sEnd_date = null; String sInout_cd = null; String sDeath_date = null; String sColor = null; String sHeight = null; String sValue = null; String sTablename = null; int patientNum = 0; Date oDate; resultFile.append(GetTimelineHeader()); boolean bOverMax = false; int conceptCount = 0; int patientCount = minPatientNum; StringBuilder patientRecord = new StringBuilder(); String currentPatientNum = null; int indexPos = 0; for (int p = 0; p < demographicsArray.size(); p++) { PatientDemographics record = demographicsArray.get(p); currentPatientNum = record.patientNumber(); if (displayDemographics) { patientRecord.append(getTimelinePatientString(currentPatientNum, record)); } else { patientRecord.append(getTimelinePatientString(currentPatientNum)); } resultFile.append(patientRecord.toString()); patientRecord = new StringBuilder(); patientCount++; conceptCount = 0; sOldConcept_cd = null; sOldStart_date = null; sOldPatient_num = ""; if ((indexPos == iNumberOfChildren) && bDisplayAll) { conceptCount = 0; while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) { patientRecord.append(getTimelineConceptString((String) conceptOrder.get(conceptCount), 1)); patientRecord.append(getTimelineEmptyDateString()); conceptCount++; } resultFile.append(patientRecord.toString()); patientRecord = new StringBuilder(); } for (int i = indexPos; i < iNumberOfChildren; i++) { if ((maxLineCount > 0) && (i > maxLineCount)) { bOverMax = true; break; } Element oChild = (Element) allChildren.get(i); sPatient_num = "";//oChild.getChild(ss_patient_num).getText( // ); if (!sPatient_num.equals(currentPatientNum) && (sOldPatient_num.equals("start")) /* * && * !sOldPatient_num * .equals( * sPatient_num * ) */) { if (bDisplayAll) { try { patientNum = Integer.parseInt(sPatient_num); conceptCount = 0; while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) { patientRecord.append( getTimelineConceptString((String) conceptOrder.get(conceptCount), 1)); patientRecord.append(getTimelineEmptyDateString()); conceptCount++; } resultFile.append(patientRecord.toString()); patientRecord = new StringBuilder(); // patientCount++; } catch (java.lang.OutOfMemoryError e) { log.error("In resultset builder 5: " + e.getMessage()); // closeConnection(oConnection); return "memory error"; } catch (Exception e) { log.error(e.getMessage()); // closeConnection(oConnection); return "error"; } conceptCount = 0; sOldConcept_cd = null; sOldStart_date = null; } break; } else if (!sPatient_num.equals(currentPatientNum) && !(sOldPatient_num.equals("start")) /* * &&! * sOldPatient_num * .equals( * sPatient_num * ) */) { if ((bDisplayAll) && (conceptCount < (conceptOrder.size()))) { while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) { patientRecord.append( getTimelineConceptString((String) conceptOrder.get(conceptCount), 1)); patientRecord.append(getTimelineEmptyDateString()); conceptCount++; } } resultFile.append(patientRecord.toString()); patientRecord = new StringBuilder(); patientCount++; conceptCount = 0; sOldConcept_cd = null; sOldStart_date = null; break; } else if (sPatient_num.equals(currentPatientNum)) { indexPos = i + 1; sOldPatient_num = sPatient_num; // if (bUseConcept) { // sConcept_cd = // oChild.getChild(ss_concept_cd).getText(); // } // else { // sConcept_cd = // oChild.getAttributeValue(ss_q_name_char); // } if (!sConcept_cd.equals(sOldConcept_cd)) { // conceptCount++; if (bDisplayAll) { for (int j = conceptCount; j < conceptOrder.size(); j++) { if (sConcept_cd.equals(conceptOrder.get(j))) { break; } else { patientRecord .append(getTimelineConceptString((String) conceptOrder.get(j), 1)); patientRecord.append(getTimelineEmptyDateString()); conceptCount++; } } } // int iNumConceptObservations = // getNumConceptObservationsRollingupStartDate // (allChildren,i); // patientRecord.append(getTimelineConceptString( // sConcept_cd,iNumConceptObservations)); conceptCount++; sOldStart_date = null; } sOldConcept_cd = sConcept_cd; // sStart_date = // oChild.getChild(ss_start_date).getText(); // if (!sStart_date.equals(sOldStart_date)) { // if (!sStart_date.equals(null)) { if ((!sStart_date.equals(null)) && ((sOldStart_date == null) || (!sStart_date.equals(sOldStart_date)))) { // sEnd_date = // oChild.getChild(ss_end_date).getText(); if ((sEnd_date == null) || (sEnd_date.trim().length() == 0)) sEnd_date = sStart_date; // sInout_cd = // oChild.getChild(ss_inout_cd).getText(); sInout_cd = ""; // sColor = oChild.getChild(ss_color_cd).getText(); // sHeight = // oChild.getChild(ss_height_cd).getText(); // sValue = oChild.getChild(ss_value_cd).getText(); // sTablename = // oChild.getChild(ss_table_name).getText(); String prefix = "C"; if (sTablename.equalsIgnoreCase("visit_dimension")) { prefix = "E"; } else if (sTablename.equalsIgnoreCase("provider_dimension")) { prefix = "P"; } // if ((sValue==null)||(sValue.length()==0)) { // sValue = prefix+" = ::"+sConcept_cd+"::"+ // "$$"+oChild.getChild(ss_patient_num).getText()+ // "$$"+oChild.getChild(ss_concept_cd).getText() + // "$$"+ChangeRsDateFull(sStart_date) ;//+"::"; } else { // sValue = prefix+" Value = " + // "::"+sConcept_cd+": "+sValue+"::"+ // "$$"+oChild.getChild(ss_patient_num).getText()+ // "$$"+oChild.getChild(ss_concept_cd).getText() + // "$$"+ChangeRsDateFull(sStart_date) ;//+"::"; } // log.debug(" "+ ChangeRsDate(sStart_date) + " -> " + // ChangeRsDate(sEnd_date)); // System.out.print(getTimelineDateString(ChangeRsDate( // sStart_date),ChangeRsDate(sEnd_date))); // System.out.print(getTimelineDateString(ChangeRsDate( // sStart_date),ChangeRsDate(sEnd_date),sConcept_cd)); if (sInout_cd.equalsIgnoreCase("I")) { if (sColor != null) patientRecord.append(getTimelineDateStringSpecial(ChangeRsDate(sStart_date), ChangeRsDate(sEnd_date), sColor)); else patientRecord.append(getTimelineDateStringSpecial(ChangeRsDate(sStart_date), ChangeRsDate(sEnd_date))); } else if (sInout_cd.equalsIgnoreCase("E")) { if (sColor != null) patientRecord.append(getTimelineDateStringEncounter(ChangeRsDate(sStart_date), ChangeRsDate(sEnd_date), sColor)); else patientRecord.append(getTimelineDateStringEncounter(ChangeRsDate(sStart_date), ChangeRsDate(sEnd_date))); } else if (sInout_cd.equalsIgnoreCase("D")) { if (sStart_date.length() == 0) { if (sColor != null) patientRecord.append(getTimelineDateStringEncounter("today", "today", sColor)); else patientRecord.append(getTimelineDateStringEncounter("today", "today")); } else { if (sColor != null) patientRecord.append( getTimelineDateStringDeath(ChangeRsDate(sStart_date), "today", sColor)); else patientRecord.append( getTimelineDateStringDeath(ChangeRsDate(sStart_date), "today", sColor)); } } else { if (sConcept_cd.equals("Death")) { if (sStart_date.length() == 0) { sStart_date = "today"; sColor = "lightbrown"; } sEnd_date = "today"; } if (sColor != null) { if (sConcept_cd.equalsIgnoreCase("EGFR")) patientRecord.append(getTimelineDateString(ChangeRsDate(sStart_date), ChangeRsDate(sEnd_date), sColor, "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=gene&cmd=Retrieve&dopt=Graphics&list_uids=1956")); else patientRecord.append(getTimelineDateStringHeight(ChangeRsDate(sStart_date), ChangeRsDate(sEnd_date), sColor, sHeight, sValue)); } else patientRecord.append(getTimelineDateStringHeight(ChangeRsDate(sStart_date), ChangeRsDate(sEnd_date), sHeight)); } } sOldStart_date = sStart_date; if (!bOverMax) { if (bDisplayAll && (indexPos == iNumberOfChildren)) { while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) { patientRecord.append( getTimelineConceptString((String) conceptOrder.get(conceptCount), 1)); patientRecord.append(getTimelineEmptyDateString()); conceptCount++; } } resultFile.append(patientRecord.toString()); patientRecord = new StringBuilder(); patientCount++; } } } if ((!bOverMax) && bDisplayAll) { while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) { patientRecord.append(getTimelineConceptString((String) conceptOrder.get(conceptCount), 1)); patientRecord.append(getTimelineEmptyDateString()); conceptCount++; } resultFile.append(patientRecord.toString()); } resultFile.append(GetTimelineFooter()); log.debug(" Total Count " + iNumberOfChildren); if (writeFile) { String i2b2File = System.getProperty("user.dir") + '/' + "i2b2xml.lld"; File oDelete = new File(i2b2File); if (oDelete != null) oDelete.delete(); RandomAccessFile f = new RandomAccessFile(i2b2File, "rw"); Lib.append(f, resultFile.toString()); f.close(); } if (bOverMax) { log.debug("reached maximum at " + new Date()); return "overmaximum"; } } catch (java.lang.OutOfMemoryError e) { log.error("In resultset builder 6: " + e.getMessage()); // closeConnection(oConnection); return "memory error"; } catch (Exception e) { log.error(e.getMessage()); // closeConnection(oConnection); return "error"; } log.debug("done at " + new Date()); return resultFile.toString(); }
From source file:com.btoddb.fastpersitentqueue.JournalFileTest.java
@Test public void testInitForReadingThenClose() throws IOException { UUID id = new UUID(); RandomAccessFile raFile = new RandomAccessFile(theFile, "rw"); raFile.writeInt(1);// w w w . j a v a 2s. co m Utils.writeUuidToFile(raFile, id); raFile.writeLong(123); raFile.close(); JournalFile jf1 = new JournalFile(theFile); jf1.initForReading(); assertThat(jf1.getVersion(), is(JournalFile.VERSION)); assertThat(jf1.getId(), is(id)); assertThat(jf1.getNumberOfEntries(), is(123L)); assertThat(jf1.isOpen(), is(true)); assertThat(jf1.isWriteMode(), is(false)); assertThat(jf1.getFilePosition(), is((long) JournalFile.HEADER_SIZE)); jf1.close(); assertThat(jf1.isOpen(), is(false)); }
From source file:de.erdesignerng.dialect.msaccess.MSAccessFileFormat.java
private static int findInFile(String aFileName, String aSearchFor) { int theBufferSize = 5242880; // 5MB boolean theSearchOn = true; String theStringBuffer;/*www. j av a 2 s . c om*/ int theOffset = 0; int theRead = theBufferSize; int thePosition; int theOverhead = aSearchFor.length() - 1; int theResult = -1; if (theBufferSize >= aSearchFor.length()) { try { File file = new File(aFileName); RandomAccessFile ra = new RandomAccessFile(aFileName, "r"); byte[] theByteBuffer = new byte[theBufferSize]; while ((theOffset < file.length()) && (theSearchOn) && (theRead == theBufferSize)) { theRead = ra.read(theByteBuffer); if (theRead >= 0) { theStringBuffer = new String(theByteBuffer, 0, theRead); thePosition = theStringBuffer.indexOf(aSearchFor); if (thePosition >= 0) { theResult = theOffset + thePosition; theSearchOn = false; LOGGER.debug( "Found '" + aSearchFor + "' in '" + aFileName + "' at position " + theResult); } else { if (theRead == theBufferSize) { theOffset += (theRead - theOverhead); ra.seek(theOffset); } } } } ra.close(); } catch (FileNotFoundException ex) { LOGGER.error("Cannot find database file " + aFileName, ex); } catch (IOException ex) { LOGGER.error("Cannot read database file " + aFileName, ex); } } else { throw new RuntimeException("The string to find is too long. Only strings of lenght up to " + theBufferSize + " can be found!"); } return theResult; }
From source file:org.apache.flume.channel.file.TestEventQueueBackingStoreFactory.java
@Test(expected = InvalidProtocolBufferException.class) public void testCorruptMeta() throws Throwable { EventQueueBackingStore backingStore = EventQueueBackingStoreFactory.get(checkpoint, 10, "test"); backingStore.close();// w w w . j a v a2 s .c o m Assert.assertTrue(checkpoint.exists()); File metaFile = Serialization.getMetaDataFile(checkpoint); Assert.assertTrue(metaFile.length() != 0); RandomAccessFile writer = new RandomAccessFile(metaFile, "rw"); writer.seek(10); writer.writeLong(new Random().nextLong()); writer.getFD().sync(); writer.close(); try { backingStore = EventQueueBackingStoreFactory.get(checkpoint, 10, "test"); } catch (BadCheckpointException ex) { throw ex.getCause(); } }
From source file:com.qubole.rubix.core.TestCachedReadRequestChain.java
@Test public void testCachedReadRequestChain() throws IOException { String filename = "/tmp/testCachedReadRequestChainFile"; populateFile(filename);/*from ww w . java 2 s .c om*/ File file = new File(filename); byte[] buffer = new byte[1000]; ReadRequest[] readRequests = { new ReadRequest(0, 100, 0, 100, buffer, 0, file.length()), new ReadRequest(200, 300, 200, 300, buffer, 100, file.length()), new ReadRequest(400, 500, 400, 500, buffer, 200, file.length()), new ReadRequest(600, 700, 600, 700, buffer, 300, file.length()), new ReadRequest(800, 900, 800, 900, buffer, 400, file.length()), new ReadRequest(1000, 1100, 1000, 1100, buffer, 500, file.length()), new ReadRequest(1200, 1300, 1200, 1300, buffer, 600, file.length()), new ReadRequest(1400, 1500, 1400, 1500, buffer, 700, file.length()), new ReadRequest(1600, 1700, 1600, 1700, buffer, 800, file.length()), new ReadRequest(1800, 1900, 1800, 1900, buffer, 900, file.length()) }; RandomAccessFile raf = new RandomAccessFile(file, "r"); CachedReadRequestChain cachedReadRequestChain = new CachedReadRequestChain(raf); for (ReadRequest rr : readRequests) { cachedReadRequestChain.addReadRequest(rr); } cachedReadRequestChain.lock(); int readSize = cachedReadRequestChain.call(); raf.close(); assertTrue("Wrong amount of data read " + readSize, readSize == 1000); String output = new String(buffer, Charset.defaultCharset()); assertTrue("Wrong data read, expected\n" + getExpectedOutput(readSize) + "\nBut got\n" + output, getExpectedOutput(readSize).equals(output)); file.delete(); }
From source file:com.qubole.rubix.core.TestCachingInputStream.java
private void writeZeros(String filename, int start, int end) throws IOException { File file = new File(filename); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(start);/* w w w . j av a2 s. co m*/ String s = "0"; StandardCharsets.UTF_8.encode(s); for (int i = 0; i < (end - start); i++) { raf.writeBytes(s); } raf.close(); }
From source file:org.apache.sling.commons.log.logback.internal.Tailer.java
public void tail(File file) throws IOException { RandomAccessFile raf = null; try {/* w w w . jav a 2s. c o m*/ raf = new RandomAccessFile(file, "r"); long startPos = getTailStartPos(raf, numOfLines); readLines(raf, startPos); } finally { try { if (raf != null) { raf.close(); } } catch (IOException ignore) { } } }
From source file:com.btoddb.fastpersitentqueue.JournalFileTest.java
@Test public void testInvalidUUID() throws Exception { // can't actuall write an invalid UUID because it's made of two variable length longs // only way to get an invalid UUID is to have a truncated file JournalFile jf1 = new JournalFile(theFile); jf1.initForWriting(new UUID()); jf1.close();/* www.j av a 2 s . c om*/ // mess up the UUID RandomAccessFile raFile = new RandomAccessFile(theFile, "rw"); Utils.writeInt(raFile, 1); Utils.writeInt(raFile, -1); raFile.setLength(raFile.getFilePointer()); raFile.close(); // Utils.writeLong(raFile, numberOfEntries.get()); JournalFile jf2 = new JournalFile(theFile); try { jf2.initForReading(); fail("should have found invalid UUID in the form of truncated file"); } catch (EOFException e) { // good! } }
From source file:com.btoddb.fastpersitentqueue.JournalFileTest.java
@Test public void testNumberOfEntriesIsIncorrect() throws Exception { JournalFile jf1 = new JournalFile(theFile); jf1.initForWriting(new UUID()); jf1.append(new FpqEntry(1, new byte[10])); jf1.close();/*from w w w.j a v a 2 s. com*/ // mess up the UUID RandomAccessFile raFile = new RandomAccessFile(theFile, "rw"); Utils.writeInt(raFile, 1); Utils.writeUuidToFile(raFile, jf1.getId()); Utils.writeLong(raFile, 123L); raFile.close(); JournalFile jf2 = new JournalFile(theFile); jf2.initForReading(); Iterator<FpqEntry> iter = jf2.iterator(); long count = 0; while (iter.hasNext()) { count++; iter.next(); } assertThat(jf2.getNumberOfEntries(), is(not(count))); assertThat(count, is(jf1.getNumberOfEntries())); }