List of usage examples for java.io RandomAccessFile close
public void close() throws IOException
From source file:com.example.android.vault.EncryptedDocument.java
/** * Encrypt and write both the metadata and content sections of this * document, reading the content from the given pipe. Internally uses * {@link ParcelFileDescriptor#checkError()} to verify that content arrives * without errors. Writes to temporary file to keep atomic view of contents, * swapping into place only when write is successful. * <p/>/*w ww .j a v a2 s . co m*/ * Pipe is left open, so caller is responsible for calling * {@link ParcelFileDescriptor#close()} or * {@link ParcelFileDescriptor#closeWithError(String)}. * * @param contentIn read end of a pipe. */ public void writeMetadataAndContent(JSONObject meta, ParcelFileDescriptor contentIn) throws IOException, GeneralSecurityException { // Write into temporary file to provide an atomic view of existing // contents during write, and also to recover from failed writes. final String tempName = mFile.getName() + ".tmp_" + Thread.currentThread().getId(); final File tempFile = new File(mFile.getParentFile(), tempName); RandomAccessFile f = new RandomAccessFile(tempFile, "rw"); try { // Truncate any existing data f.setLength(0); // Write content first to detect size if (contentIn != null) { f.seek(CONTENT_OFFSET); final int plainLength = writeSection(f, new FileInputStream(contentIn.getFileDescriptor())); meta.put(Document.COLUMN_SIZE, plainLength); // Verify that remote side of pipe finished okay; if they // crashed or indicated an error then this throws and we // leave the original file intact and clean up temp below. contentIn.checkError(); } meta.put(Document.COLUMN_DOCUMENT_ID, mDocId); meta.put(Document.COLUMN_LAST_MODIFIED, System.currentTimeMillis()); // Rewind and write metadata section f.seek(0); f.writeInt(MAGIC_NUMBER); final ByteArrayInputStream metaIn = new ByteArrayInputStream( meta.toString().getBytes(StandardCharsets.UTF_8)); writeSection(f, metaIn); if (f.getFilePointer() > CONTENT_OFFSET) { throw new IOException("Metadata section was too large"); } // Everything written fine, atomically swap new data into place. // fsync() before close would be overkill, since rename() is an // atomic barrier. f.close(); tempFile.renameTo(mFile); } catch (JSONException e) { throw new IOException(e); } finally { // Regardless of what happens, always try cleaning up. f.close(); tempFile.delete(); } }
From source file:edu.harvard.i2b2.adminTool.dataModel.PatientMappingFactory.java
@SuppressWarnings("unchecked") public String generateTimelineData(String result, ArrayList<TimelineRow> rows, boolean writeFile, boolean displayAll, boolean displayDemographics, final MainComposite explorer) { try {//from ww w . j a va 2 s. c o m PDOResponseMessageModel pdoresponsefactory = new PDOResponseMessageModel(); StatusType statusType = pdoresponsefactory.getStatusFromResponseXML(result); if (!statusType.getType().equalsIgnoreCase("DONE")) { return "error"; } JAXBUtil jaxbUtil = PatientMappingJAXBUtil.getJAXBUtil(); JAXBElement jaxbElement = jaxbUtil.unMashallFromString(result); ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue(); BodyType bodyType = messageType.getMessageBody(); PatientDataResponseType responseType = (PatientDataResponseType) new JAXBUnWrapHelper() .getObjectByClass(bodyType.getAny(), PatientDataResponseType.class); PageType pageType = responseType.getPage(); if (pageType != null) { final int returnLastIndex = pageType.getPagingByPatients().getPatientsReturned().getLastIndex() .intValue(); final int returnFirstIndex = pageType.getPagingByPatients().getPatientsReturned().getFirstIndex() .intValue(); final int requestLastIndex = pageType.getPagingByPatients().getPatientsRequested().getLastIndex() .intValue(); if (returnLastIndex < requestLastIndex) { // System.out.println("Can't return all the requested "+ // requestIndex+" patients, only "+returnIndex+" patients returned"); explorer.getDisplay().syncExec(new Runnable() { public void run() { // MessageBox mBox = new MessageBox(explorer // .getShell(), SWT.ICON_INFORMATION // | SWT.OK ); // mBox.setText("Please Note ..."); // mBox.setMessage("Only "+(returnLastIndex-returnFirstIndex+1)+" patients returned"); // mBox.open(); if (explorer.runMode() >= 0) { explorer.setIncrementNumber(returnLastIndex - returnFirstIndex + 1); } else if (explorer.runMode() == -1) { explorer.setDecreaseNumber(returnLastIndex - returnFirstIndex + 1); } } }); explorer.returnedNumber(returnLastIndex - returnFirstIndex + 1); } else { explorer.returnedNumber(-1); } } else { explorer.getDisplay().syncExec(new Runnable() { public void run() { // MessageBox mBox = new MessageBox(explorer // .getShell(), SWT.ICON_INFORMATION // | SWT.OK ); // mBox.setText("Please Note ..."); // mBox.setMessage("Only "+(returnLastIndex-returnFirstIndex+1)+" patients returned"); // mBox.open(); if (explorer.runMode() >= 0) { explorer.setIncrementNumber(-1); } else if (explorer.runMode() == -1) { explorer.setDecreaseNumber(-1); } } }); } 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:"); String curPNum = "-1"; 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(curPNum.equals("-1")) { curPNum = new String(pnum); //} 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(); XMLGregorianCalendar curStartDate = null; //int currentInstanceNum = 0; //String currentConcept = ""; ArrayList<ObservationType> facts = new ArrayList<ObservationType>(); ObservationType curFact = null; boolean recorded = false; String sStart_date = null; String sEnd_date = null; // 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.panelName())) { observationFactSet = tmpFactSet; path = observationFactSet.getPanelName(); currentRow = row; break; } } if (observationFactSet == null) { continue; } for (int k = 0; k < observationFactSet.getObservation().size(); k++) { ObservationType obsFactType = observationFactSet.getObservation().get(k); //if(curFact == null) { //curFact = obsFactType; //} //facts.add(obsFactType); if (pnum.equals(obsFactType.getPatientId().getValue())) { /* * if ((curStartDate != null) && * (obsFactType.getStartDate().compare( * curStartDate) == DatatypeConstants.EQUAL)) { * continue; } */ if (curFact == null) { curFact = obsFactType; } if (curStartDate == null) { curStartDate = obsFactType.getStartDate(); } sStart_date = obsFactType.getStartDate().getMonth() + "-" + obsFactType.getStartDate().getDay() + "-" + obsFactType.getStartDate().getYear() + " 12:00"; 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(); } PDOValueModel valdp = null; if (false) {//pset.hasValueDisplayProperty) { for (int n = 0; n < pset.valDisplayProperties.size(); n++) { PDOValueModel tmpvaldp = pset.valDisplayProperties.get(n); // if (tmpvaldp.inRange(nval)) { valdp = tmpvaldp; // break; // } } String sValue = getSValue(obsFactType.getConceptCd().getName(), 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 = ""; if (sameInstance(curFact, obsFactType)) { //if(recorded) { facts.add(obsFactType); //recorded = false; continue; //} /*sValue = getSValueSame(obsFactType.getConceptCd().getName(), obsFactType, false); if ((curStartDate != null) && (obsFactType.getStartDate() .compare(curStartDate) == DatatypeConstants.EQUAL)) { resultString .append(getTimelineDateStringHeightSame( sStart_date, sEnd_date, "slateblue", pset.height, sValue)); } else { resultString .append(getTimelineDateStringHeightSame( sStart_date, sEnd_date, pset.color, pset.height, sValue)); }*/ } //else { sValue = getSValue(curFact.getConceptCd().getName(), facts, false); //} sStart_date = curFact.getStartDate().getMonth() + "-" + curFact.getStartDate().getDay() + "-" + curFact.getStartDate().getYear() + " 12:00"; if (curFact.getEndDate() == null) { sEnd_date = sStart_date; } else { sEnd_date = curFact.getEndDate().getMonth() + "-" + curFact.getEndDate().getDay() + "-" + curFact.getEndDate().getYear() + " 12:00"; } //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++; recorded = false; facts.clear(); facts.add(obsFactType); curStartDate = obsFactType.getStartDate(); curFact = obsFactType; } else { if (recorded || facts.size() == 0) { curPNum = new String(pnum); continue; } sStart_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-" + curStartDate.getYear() + " 12:00"; //if (obsFactType.getEndDate() == null) { //sEnd_date = sStart_date; //} else { sEnd_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-" + curStartDate.getYear() + " 12:00"; //} //curFact = null; String sValue = getSValue(curFact.getConceptCd().getName(), facts, 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++; recorded = true; facts.clear(); curStartDate = null;//obsFactType.getStartDate(); curFact = null;//obsFactType; curPNum = new String(pnum); } } } if (total > 0) { // log.debug("-- "+path+" has "+total+" events"); resultFile.append(getTimelineConceptString(row.displayName, total)); // log.debug(resultString.toString()); resultFile.append(resultString); total = 0; ////rdtr } else { // display all if (displayAll) { // log.debug("-- "+path+" has "+total+" events"); resultFile.append(getTimelineConceptString(row.displayName, 1)); // log.debug(getTimelineEmptyDateString()); resultFile.append(getTimelineEmptyDateString()); } } if (recorded || facts.size() == 0) { curPNum = new String(pnum); continue; } sStart_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-" + curStartDate.getYear() + " 12:00"; //if (obsFactType.getEndDate() == null) { //sEnd_date = sStart_date; //} else { sEnd_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-" + curStartDate.getYear() + " 12:00"; //} //curFact = null; String sValue = getSValue(curFact.getConceptCd().getName(), facts, false); resultString .append(getTimelineDateStringHeight(sStart_date, sEnd_date, "navyblue", "p10", sValue)); total++; recorded = true; facts.clear(); //curStartDate = obsFactType.getStartDate(); //curFact = obsFactType; curPNum = new String(pnum); if (total > 0) { // log.debug("-- "+path+" has "+total+" events"); resultFile.append(getTimelineConceptString(row.displayName, total)); // log.debug(resultString.toString()); resultFile.append(resultString); } } } 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:com.owncloud.android.operations.ChunkedUploadFileOperation.java
@Override protected int uploadFile(WebdavClient client) throws HttpException, IOException { int status = -1; FileChannel channel = null;/* www. j a va2 s. c o m*/ RandomAccessFile raf = null; try { File file = new File(getStoragePath()); raf = new RandomAccessFile(file, "r"); channel = raf.getChannel(); mEntity = new ChunkFromFileChannelRequestEntity(channel, getMimeType(), CHUNK_SIZE, file); ((ProgressiveDataTransferer) mEntity).addDatatransferProgressListeners(getDataTransferListeners()); long offset = 0; String uriPrefix = client.getBaseUri() + WebdavUtils.encodePath(getRemotePath()) + "-chunking-" + Math.abs((new Random()).nextInt(9000) + 1000) + "-"; long chunkCount = (long) Math.ceil((double) file.length() / CHUNK_SIZE); for (int chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++, offset += CHUNK_SIZE) { if (mPutMethod != null) { mPutMethod.releaseConnection(); // let the connection available for other methods } mPutMethod = new PutMethod(uriPrefix + chunkCount + "-" + chunkIndex); mPutMethod.addRequestHeader(OC_CHUNKED_HEADER, OC_CHUNKED_HEADER); ((ChunkFromFileChannelRequestEntity) mEntity).setOffset(offset); mPutMethod.setRequestEntity(mEntity); status = client.executeMethod(mPutMethod); client.exhaustResponse(mPutMethod.getResponseBodyAsStream()); Log_OC.d(TAG, "Upload of " + getStoragePath() + " to " + getRemotePath() + ", chunk index " + chunkIndex + ", count " + chunkCount + ", HTTP result status " + status); if (!isSuccess(status)) break; } } finally { if (channel != null) channel.close(); if (raf != null) raf.close(); if (mPutMethod != null) mPutMethod.releaseConnection(); // let the connection available for other methods } return status; }
From source file:com.siblinks.ws.service.impl.MentorServiceImpl.java
/** * {@inheritDoc}// w w w . j a va2 s . co m */ @Override @RequestMapping(value = "/getImageAboutMentor/{id}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) public ResponseEntity<byte[]> getImageAboutMentor(@PathVariable(value = "id") final String id) { ResponseEntity<byte[]> responseEntity = null; try { Map<String, String> queryParams = new HashMap<String, String>(); List<Object> readObject = null; queryParams.put("id", id); String entityName = SibConstants.SqlMapper.SQL_GET_IMAGE_ABOUT_MENTOR; String path = null; readObject = dao.readObjects(entityName, queryParams); if (((Map) readObject.get(0)).get(Parameters.IMAGE) != null) { path = ((Map) readObject.get(0)).get(Parameters.IMAGE).toString(); RandomAccessFile t = null; byte[] r = null; try { t = new RandomAccessFile(path, "r"); r = new byte[(int) t.length()]; t.readFully(r); responseEntity = new ResponseEntity<byte[]>(r, new HttpHeaders(), HttpStatus.OK); } catch (IOException e) { logger.debug("Some thing wrong", e); responseEntity = new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND); } finally { // Close file if (t != null) { try { t.close(); } catch (IOException e) { // Do nothing } } } } else { responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT); } } catch (DAOException e) { e.printStackTrace(); new SimpleResponse(SibConstants.FAILURE, "Mentor", "getImageAboutMentor", e.getMessage()); } return responseEntity; }
From source file:com.koda.integ.hbase.storage.FileExtStorage.java
/** * Put file back to the pool/*from ww w . j a va 2s . c o m*/ * TODO: race condition * * @param id the id * @param file the file */ private void putFile(int id, RandomAccessFile file) { Queue<RandomAccessFile> fileReaders = readers.get(id); boolean result = false; if (fileReaders == null) { // This means that file has been deleted result = false; } else { result = fileReaders.offer(file); // Put back if present // Make sure that file has not been deleted if (readers.replace(id, fileReaders) == null) { result = false; // clear queue fileReaders.clear(); } } if (result == false) { try { file.close(); } catch (IOException e) { LOG.error(e); } } }
From source file:com.siblinks.ws.service.impl.ArticleServiceImpl.java
/** * {@inheritDoc}/*w w w . j ava2s.c o m*/ * */ @SuppressWarnings("resource") @Override @RequestMapping(value = "/getImageArticle/{arId}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) public ResponseEntity<byte[]> getImageArticle(@PathVariable(value = "arId") final String arId) throws IOException { RandomAccessFile t = null; Object[] queryParams = { arId }; String path = null; ResponseEntity<byte[]> responseEntity = null; try { List<Object> readObject = dao.readObjects(SibConstants.SqlMapper.SQL_GET_IMAGE_ARTICLE, queryParams); if (((Map) readObject.get(0)).get(Parameters.IMAGE) != null) { path = ((Map) readObject.get(0)).get(Parameters.IMAGE).toString(); // System.out.print(Paths.get("").toAbsolutePath()+path); path = Paths.get("").toAbsolutePath() + path; byte[] r = null; try { t = new RandomAccessFile(path, "r"); r = new byte[(int) t.length()]; t.readFully(r); } catch (FileNotFoundException e) { e.printStackTrace(); } final HttpHeaders headers = new HttpHeaders(); responseEntity = new ResponseEntity<byte[]>(r, headers, HttpStatus.OK); } else { responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT); } } catch (Exception e) { e.printStackTrace(); responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT); } finally { if (t != null) { t.close(); } } return responseEntity; }
From source file:com.edgenius.wiki.service.impl.SitemapServiceImpl.java
private void appendSitemapIndex(String sitemap) throws IOException { File sitemapIndexFile = new File(mapResourcesRoot.getFile(), SITEMAP_INDEX_NAME); if (!sitemapIndexFile.exists()) { //if a new sitemap file List<String> lines = new ArrayList<String>(); lines.add("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); lines.add("<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"); lines.add("</sitemapindex>"); FileUtils.writeLines(sitemapIndexFile, lines); }/* ww w.j ava 2s. com*/ RandomAccessFile rfile = new RandomAccessFile(sitemapIndexFile, "rw"); FileChannel channel = rfile.getChannel(); //this new content will append to end of file before XML end tag StringBuilder lines = new StringBuilder(); lines.append(" <sitemap>\n"); lines.append(" <loc>" + WebUtil.getHostAppURL() + SITEMAP_URL_CONTEXT + sitemap + "</loc>\n"); lines.append(" <lastmod>" + TIME_FORMAT.format(new Date()) + " </lastmod>\n"); lines.append(" </sitemap>\n"); //the last tag will be overwrite, so append it again to new content. lines.append(SITEMAP_INDEX_TAIL_FLAG); byte[] content = lines.toString().getBytes(); ByteBuffer byteBuf = ByteBuffer.allocate(512); // seek first int len = 0, headIdx = 0; long tailIdx = channel.size() - 512; tailIdx = tailIdx < 0 ? 0 : tailIdx; long headPos = -1; StringBuilder header = new StringBuilder(); while ((len = channel.read(byteBuf, tailIdx)) > 0) { byteBuf.rewind(); byte[] dst = new byte[len]; byteBuf.get(dst, 0, len); header.append(new String(dst, "UTF8")); headIdx = header.indexOf(SITEMAP_INDEX_TAIL_FLAG); if (headIdx != -1) { headPos = channel.size() - header.substring(headIdx).getBytes().length; break; } } FileLock lock = channel.tryLock(headPos, content.length, false); try { channel.write(ByteBuffer.wrap(content), headPos); } finally { lock.release(); } channel.force(false); rfile.close(); }
From source file:com.datatorrent.flume.storage.HDFSStorageTest.java
@Test public void testNext() throws IOException { RandomAccessFile r = new RandomAccessFile(testMeta.testFile, "r"); r.seek(0);/*from w w w.j ava 2s .c om*/ Assert.assertNull(storage.retrieve(new byte[8])); byte[] b = r.readLine().getBytes(); storage.store(new Slice(b, 0, b.length)); byte[] b1 = r.readLine().getBytes(); storage.store(new Slice(b1, 0, b1.length)); storage.store(new Slice(b, 0, b.length)); storage.flush(); storage.store(new Slice(b1, 0, b1.length)); storage.store(new Slice(b, 0, b.length)); storage.flush(); byte[] data = storage.retrieve(new byte[8]); byte[] tempData = new byte[data.length - 8]; System.arraycopy(data, 8, tempData, 0, tempData.length); Assert.assertEquals("matched the stored value with retrieved value", new String(b), new String(tempData)); data = storage.retrieveNext(); tempData = new byte[data.length - 8]; System.arraycopy(data, 8, tempData, 0, tempData.length); Assert.assertEquals("matched the stored value with retrieved value", new String(b1), new String(tempData)); data = storage.retrieveNext(); tempData = new byte[data.length - 8]; System.arraycopy(data, 8, tempData, 0, tempData.length); Assert.assertEquals("matched the stored value with retrieved value", new String(b), new String(tempData)); r.close(); }
From source file:com.android.volley.cache.ACache.java
/** * ? byte ?// w ww . j a va 2 s . c o m * * @param key * @return byte ? */ // public byte[] getAsBinary(String key) { public BinaryShell getAsBinary(String key) { RandomAccessFile RAFile = null; // boolean removeFile = false; try { File file = mCache.get(key); if (!file.exists()) return null; RAFile = new RandomAccessFile(file, "r"); byte[] byteArray = new byte[(int) RAFile.length()]; RAFile.read(byteArray); BinaryShell shell = new BinaryShell(); shell.content = Utils.clearDateInfo(byteArray); if (!Utils.isDue(byteArray)) { shell.outOfDate = false; } else { shell.outOfDate = true; } // if (!Utils.isDue(byteArray)) { // return Utils.clearDateInfo(byteArray); // } else { // removeFile = true; // return null; // } return shell; } catch (Exception e) { e.printStackTrace(); return null; } finally { if (RAFile != null) { try { RAFile.close(); } catch (IOException e) { e.printStackTrace(); } } // if (removeFile) // remove(key); } }
From source file:org.carewebframework.api.logging.LogFileTailer.java
/** * Typically executed via a <code>new Thread(FileTailer).start()</code> */// ww w . ja v a 2s.c o m @Override public void run() { // The file pointer keeps track of where we are in the file long filePointer = 0; final long startTime = new Date().getTime(); // Determine start point if (this.startAtBeginning) { filePointer = 0; } else { filePointer = this.file.length(); } try { // Start tailing this.tailing = true; RandomAccessFile file = new RandomAccessFile(this.file, "r"); while (isTailing()) { //check to see if maxActiveInterval has been exceeded if (new Date().getTime() - startTime > this.maxActiveInterval) { if (log.isWarnEnabled()) { log.warn("FileTailer exceeded maxActiveInterval: " + this.maxActiveInterval); } stopTailing(); fireMaxActiveIntervalExceeded(); } try { // Compare the length of the file to the file pointer final long fileLength = this.file.length(); if (fileLength < filePointer) { // file must have been rotated or deleted; // reopen the file and reset the file pointer file = new RandomAccessFile(this.file, "r"); filePointer = 0; } if (fileLength > filePointer) { // There is data to read file.seek(filePointer); String line = file.readLine(); while (line != null) { fireNewFileLine(line); line = file.readLine(); } filePointer = file.getFilePointer(); } // Sleep for the specified interval Thread.sleep(this.interval); } catch (final Exception e) { log.error(e.getMessage(), e); } } // Close the file that we are tailing file.close(); } catch (final Exception e) { log.error(e.getMessage(), e); } }