List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
From source file:com.devilyang.musicstation.cache.ACache.java
/** * ? byte ?// w w w . j av a2 s . c o m * * @param key * @return byte ? */ public byte[] getAsBinary(String key) { RandomAccessFile RAFile = null; boolean removeFile = false; try { File file = mCacheManager.get(key); if (!file.exists()) return null; RAFile = new RandomAccessFile(file, "r"); byte[] byteArray = new byte[(int) RAFile.length()]; RAFile.read(byteArray); if (!Utils.isDue(byteArray)) { return Utils.clearDateInfo(byteArray); } else { removeFile = true; return null; } } 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:dk.statsbiblioteket.util.LineReader.java
/** * Ensure that the {@link #channelOut} is ready for writing. * * @throws IOException if channelOut could not be opened. * @throws IllegalStateException if the file opened in read-only mode.. *//* w w w . java 2 s .c o m*/ private void checkOutputFile() throws IOException { if (!writable) { throw new IllegalStateException(String.format("The file '%s' has been opened in read-only mode", file)); } if (outOpen) { return; } log.trace("Opening output channel for '" + file + "'"); output = new RandomAccessFile(file, "rw"); // output = new FileOutputStream(file, true); channelOut = output.getChannel(); outOpen = true; }
From source file:eu.stratosphere.nephele.services.iomanager.IOManagerPerformanceBenchmark.java
@SuppressWarnings("resource") private final void speedTestNIO(int bufferSize, boolean direct) throws IOException { final Channel.ID tmpChannel = ioManager.createChannel(); File tempFile = null;/*from w ww .j a v a 2 s. co m*/ FileChannel fs = null; try { tempFile = new File(tmpChannel.getPath()); RandomAccessFile raf = new RandomAccessFile(tempFile, "rw"); fs = raf.getChannel(); ByteBuffer buf = direct ? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize); long writeStart = System.currentTimeMillis(); int valsLeft = NUM_INTS_WRITTEN; while (valsLeft-- > 0) { if (buf.remaining() < 4) { buf.flip(); fs.write(buf); buf.clear(); } buf.putInt(valsLeft); } if (buf.position() > 0) { buf.flip(); fs.write(buf); } fs.close(); raf.close(); fs = null; long writeElapsed = System.currentTimeMillis() - writeStart; // ---------------------------------------------------------------- raf = new RandomAccessFile(tempFile, "r"); fs = raf.getChannel(); buf.clear(); long readStart = System.currentTimeMillis(); fs.read(buf); buf.flip(); valsLeft = NUM_INTS_WRITTEN; while (valsLeft-- > 0) { if (buf.remaining() < 4) { buf.compact(); fs.read(buf); buf.flip(); } if (buf.getInt() != valsLeft) { throw new IOException(); } } fs.close(); raf.close(); long readElapsed = System.currentTimeMillis() - readStart; LOG.info("NIO Channel with buffer " + bufferSize + ": write " + writeElapsed + " msecs, read " + readElapsed + " msecs."); } finally { // close if possible if (fs != null) { fs.close(); fs = null; } // try to delete the file if (tempFile != null) { tempFile.delete(); } } }
From source file:edu.umass.cs.gigapaxos.AbstractPaxosLogger.java
/** * @param strID//ww w . java2 s. c o m */ public static final void fileLock(Object strID) { RandomAccessFile raf = null; try { String logdir = getLocksDir(); (new File(logdir)).mkdirs(); String filename = logdir + "/" + strID; File file = new File(filename); boolean created = file.createNewFile(); FileLock lock = (raf = new RandomAccessFile(file, "rw")).getChannel().tryLock(); if (lock == null) throw new RuntimeException("Unable to start node " + strID + " likely because node " + strID + " from " + Util.readFileAsString(filename).split("\n")[0].trim().replaceAll("#", "") + " is already running"); // lock!=null if (created && PaxosConfig.getPropertiesFile() != null) { raf.write(("#" + PaxosConfig.getPropertiesFile() + "\n").getBytes()); raf.write(Util.readFileAsString(PaxosConfig.getPropertiesFile()).getBytes()); } } catch (IOException e) { e.printStackTrace(); if (raf != null) try { raf.close(); } catch (IOException e1) { e1.printStackTrace(); } } }
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 w w 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"; } 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:com.aol.advertising.qiao.injector.file.AbstractFileTailer.java
protected RandomAccessFile openFileQuietly(File file) { RandomAccessFile reader = null; while (running && reader == null) { try {/*ww w .j a v a 2 s . c o m*/ reader = new RandomAccessFile(file, RAF_MODE); } catch (FileNotFoundException e) { } if (reader != null) return reader; boolean timed_out = CommonUtils.sleepQuietly(fileCheckDelayMillis); if (!timed_out) // interrupted break; } return null; }
From source file:GridFDock.DataDistribute.java
public Status uploadFile(String remoteFile, File localFile, FTPClient ftpClient, long remoteSize) throws IOException { long step = localFile.length() / 100; long process = 0; long localreadbytes = 0L; boolean tmp2 = true; Status result = null;//w ww .jav a2s .com ftpClient.setFileType(FTP.BINARY_FILE_TYPE); while (tmp2) { RandomAccessFile raf = new RandomAccessFile(localFile, "r"); OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes(CODING_1), CODING_2)); if (remoteSize > 0) { ftpClient.setRestartOffset(remoteSize); process = remoteSize / step; raf.seek(remoteSize); localreadbytes = remoteSize; } byte[] bytes = new byte[1024]; int c; while ((c = raf.read(bytes)) != -1) { out.write(bytes, 0, c); localreadbytes += c; if (localreadbytes / step != process) { process = localreadbytes / step; // System.out.println("Upload Progress" + process); } } out.flush(); raf.close(); out.close(); boolean judge = ftpClient.completePendingCommand(); if (judge) { result = Status.Upload_From_Break_Success; tmp2 = false; } else { result = Status.Upload_New_File_Failed; } } return result; }
From source file:TestFuseDFS.java
/** * Test random access to a file//from w ww . j ava2 s . c o m */ @Test public void testRandomAccess() throws IOException { final String contents = "hello world"; File f = new File(mountPoint, "file1"); createFile(f, contents); RandomAccessFile raf = new RandomAccessFile(f, "rw"); raf.seek(f.length()); try { raf.write('b'); } catch (IOException e) { // Expected: fuse-dfs not yet support append assertEquals("Operation not supported", e.getMessage()); } finally { raf.close(); } raf = new RandomAccessFile(f, "rw"); raf.seek(0); try { raf.write('b'); fail("Over-wrote existing bytes"); } catch (IOException e) { // Expected: can-not overwrite a file assertEquals("Invalid argument", e.getMessage()); } finally { raf.close(); } execAssertSucceeds("rm " + f.getAbsolutePath()); }
From source file:be.roots.taconic.pricingguide.util.iTextUtil.java
public static byte[] embedFont(byte[] pdf, String fontFileName, String fontName) throws IOException, DocumentException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { // the font file RandomAccessFile raf = new RandomAccessFile(fontFileName, "r"); byte fontfile[] = new byte[(int) raf.length()]; raf.readFully(fontfile);//from w w w . j ava 2 s. com raf.close(); // create a new stream for the font file PdfStream stream = new PdfStream(fontfile); stream.flateCompress(); stream.put(PdfName.LENGTH1, new PdfNumber(fontfile.length)); // create a reader object PdfReader reader = new PdfReader(pdf); int n = reader.getXrefSize(); PdfObject object; PdfDictionary font; PdfStamper stamper = new PdfStamper(reader, baos); PdfName fontname = new PdfName(fontName); for (int i = 0; i < n; i++) { object = reader.getPdfObject(i); if (object == null || !object.isDictionary()) continue; font = (PdfDictionary) object; if (PdfName.FONTDESCRIPTOR.equals(font.get(PdfName.TYPE1)) && fontname.equals(font.get(PdfName.FONTNAME))) { PdfIndirectObject objref = stamper.getWriter().addToBody(stream); font.put(PdfName.FONTFILE2, objref.getIndirectReference()); } } stamper.close(); reader.close(); return baos.toByteArray(); } }
From source file:com.slytechs.capture.FileFactory.java
public long countPackets(File dst) throws IOException, FileFormatException { final FormatType type = formatType(dst); if (type == null) { throw new FileFormatException("Unrecognized file format"); }//from ww w. j a v a 2 s . co m final long count; switch (type) { case Other: final ReadableByteChannel channel = new RandomAccessFile(dst, "r").getChannel(); final InputCapture<? extends CapturePacket> input = newInput(channel, null); count = Captures.count(input.getPacketIterator()); input.close(); break; default: final FileCapture capture = openFile(dst); count = capture.getPacketCount(); capture.close(); break; } return count; }