List of usage examples for java.io RandomAccessFile seek
public void seek(long pos) throws IOException
From source file:com.phonegap.FileUtils.java
/** * Write contents of file.//from ww w .ja v a 2 s. co m * * @param filename The name of the file. * @param data The contents of the file. * @param offset The position to begin writing the file. * @throws FileNotFoundException, IOException */ public long write(String filename, String data, long offset) throws FileNotFoundException, IOException { RandomAccessFile file = new RandomAccessFile(filename, "rw"); file.seek(offset); file.writeBytes(data); file.close(); return data.length(); }
From source file:dk.netarkivet.common.utils.cdx.BinSearch.java
/** Returns the position of a line between startpos and endpos. * If no line other than the one starting at startpos can be found, * returns -1. Also sets the file pointer to the start of the line. * @param in The file to read from// w w w . ja va2 s . com * @param startpos The lower bound for the position. Must be the * start of a line. * @param endpos The upper bound for the position. Must be the start of * a line or EOF. * @return The position of a line s.t. startpos < returnval < endpos, * or -1 if no such line can be found. * @throws IOException If some I/O error occurs */ private static long findMiddleLine(RandomAccessFile in, long startpos, long endpos) throws IOException { // First check that there is a middle line at all. // If there is a line after startpos, but before endpos, // we remember it and as soon as we hit that line. long firstmiddleline = skipToLine(in, startpos); if (firstmiddleline == endpos) { return -1; } long newmidpos = endpos; int div = 1; while (newmidpos == endpos) { // Drat, newmidpos is not far enough back. // Divide back until we find a previous line. div *= 2; // Find an earlier point, half as far from startpos as the previous newmidpos = startpos + (endpos - startpos) / div; // If we get beyond the found line after the start line, just // return that. if (newmidpos < firstmiddleline) { newmidpos = firstmiddleline; in.seek(newmidpos); break; } // Now find the first line after the new middle newmidpos = skipToLine(in, newmidpos); } // Now the midpos should be != startpos && != endpos assert newmidpos != startpos : "Invariant violated: Newmidpos > startpos"; return newmidpos; }
From source file:fr.gael.dhus.server.ftp.DHuSFtpProduct.java
@Override public InputStream createInputStream(long offset) throws IOException { File file = new File(product.getDownloadablePath()); logger.debug("Retrieving File stream from " + file.getPath()); /*/* www. j a v a 2 s. co m*/ return new FileInputStream(file); */ // permission check if (!doesExist()) { throw new IOException("No read permission : " + file.getName()); } // move to the appropriate offset and create input stream final RandomAccessFile raf = new RandomAccessFile(file, "r"); try { raf.seek(offset); // The IBM jre needs to have both the stream and the random access file // objects closed to actually close the file return new RegulatedInputStream.Builder(new FileInputStream(raf.getFD()) { public void close() throws IOException { super.close(); raf.close(); } }, TrafficDirection.OUTBOUND).userName(user.getName()) .copyStreamListener(new DownloadActionRecordListener(product.getUuid(), product.getIdentifier(), vfsService.getDhusUserFromFtpUser(user))) .build(); } catch (IOException e) { raf.close(); throw e; } }
From source file:com.piaoyou.util.FileUtil.java
public static String[] getLastLines(File file, int linesToReturn) throws IOException, FileNotFoundException { final int AVERAGE_CHARS_PER_LINE = 250; final int BYTES_PER_CHAR = 2; RandomAccessFile randomAccessFile = null; StringBuffer buffer = new StringBuffer(linesToReturn * AVERAGE_CHARS_PER_LINE); int lineTotal = 0; try {//from www .jav a2 s. c o m randomAccessFile = new RandomAccessFile(file, "r"); long byteTotal = randomAccessFile.length(); long byteEstimateToRead = linesToReturn * AVERAGE_CHARS_PER_LINE * BYTES_PER_CHAR; long offset = byteTotal - byteEstimateToRead; if (offset < 0) { offset = 0; } randomAccessFile.seek(offset); //log.debug("SKIP IS ::" + offset); String line = null; String lineUTF8 = null; while ((line = randomAccessFile.readLine()) != null) { lineUTF8 = new String(line.getBytes("ISO8859_1"), "UTF-8"); lineTotal++; buffer.append(lineUTF8).append('\n'); } } finally { if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException ex) { } } } String[] resultLines = new String[linesToReturn]; BufferedReader in = null; try { in = new BufferedReader(new StringReader(buffer.toString())); int start = lineTotal /* + 2 */ - linesToReturn; // Ex : 55 - 10 = 45 ~ offset if (start < 0) start = 0; // not start line for (int i = 0; i < start; i++) { in.readLine(); // loop until the offset. Ex: loop 0, 1 ~~ 2 lines } int i = 0; String line = null; while ((line = in.readLine()) != null) { resultLines[i] = line; i++; } } catch (IOException ie) { log.error("Error" + ie); throw ie; } finally { if (in != null) { try { in.close(); } catch (IOException ex) { } } } return resultLines; }
From source file:org.kalypso.shape.shp.SHPFile.java
/** * returns the minimum bound rectangle of RecNo's Geometrie of the shape-file <BR> *///from ww w . j a v a2 s . c o m public SHPEnvelope getEnvelope(final SHXRecord record) throws IOException { final RandomAccessFile raf = getRandomAccessFile(); final int position = record.getOffset() * 2; raf.seek(position + 8); final ShapeType shpType = ShapeType.valueOf(DataUtils.readLEInt(raf)); /* * only for PolyLines, Polygons and MultiPoints minimum bounding rectangles are defined */ if (shpType == ShapeType.POLYLINE || shpType == ShapeType.POLYGON || shpType == ShapeType.MULTIPOINT || shpType == ShapeType.POLYLINEZ || shpType == ShapeType.POLYGONZ || shpType == ShapeType.MULTIPOINTZ) return new SHPEnvelope(raf); return null; }
From source file:org.apache.bookkeeper.bookie.EntryLogTest.java
/** * Explicitely try to recover using the ledgers map index at the end of the entry log *///from w w w. j a v a 2s. c o m @Test(timeout = 60000) public void testRecoverFromLedgersMapOnV0EntryLog() throws Exception { File tmpDir = createTempDir("bkTest", ".dir"); File curDir = Bookie.getCurrentDirectory(tmpDir); Bookie.checkDirectoryStructure(curDir); int gcWaitTime = 1000; ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setGcWaitTime(gcWaitTime); conf.setLedgerDirNames(new String[] { tmpDir.toString() }); Bookie bookie = new Bookie(conf); // create some entries EntryLogger logger = ((InterleavedLedgerStorage) bookie.ledgerStorage).entryLogger; logger.addEntry(1, generateEntry(1, 1)); logger.addEntry(3, generateEntry(3, 1)); logger.addEntry(2, generateEntry(2, 1)); logger.addEntry(1, generateEntry(1, 2)); logger.rollLog(); // Rewrite the entry log header to be on V0 format File f = new File(curDir, "0.log"); RandomAccessFile raf = new RandomAccessFile(f, "rw"); raf.seek(EntryLogger.HEADER_VERSION_POSITION); // Write zeros to indicate V0 + no ledgers map info raf.write(new byte[4 + 8]); raf.close(); // now see which ledgers are in the log logger = new EntryLogger(conf, bookie.getLedgerDirsManager()); try { logger.extractEntryLogMetadataFromIndex(0L); fail("Should not be possible to recover from ledgers map index"); } catch (IOException e) { // Ok } // Public method should succeed by falling back to scanning the file EntryLogMetadata meta = logger.getEntryLogMetadata(0L); LOG.info("Extracted Meta From Entry Log {}", meta); assertEquals(60, meta.getLedgersMap().get(1L).longValue()); assertEquals(30, meta.getLedgersMap().get(2L).longValue()); assertEquals(30, meta.getLedgersMap().get(3L).longValue()); assertNull(meta.getLedgersMap().get(4L)); assertEquals(120, meta.getTotalSize()); assertEquals(120, meta.getRemainingSize()); }
From source file:org.apache.activemq.store.kahadb.KahaDBStoreRecoveryBrokerTest.java
@Override @SuppressWarnings("resource") protected BrokerService createRestartedBroker() throws Exception { // corrupting index File index = new File(kahaDbDirectoryName + "/db.data"); RandomAccessFile raf = new RandomAccessFile(index, "rw"); switch (failTest) { case FailToLoad: index.delete();//from w ww. j a v a 2 s. c o m raf = new RandomAccessFile(index, "rw"); raf.seek(index.length()); raf.writeBytes("corrupt"); break; case LoadInvalid: // page size 0 raf.seek(0); raf.writeBytes("corrupt and cannot load metadata"); break; case LoadCorrupt: // loadable but invalid metadata // location of order index low priority index for first destination... raf.seek(8 * 1024 + 57); raf.writeLong(Integer.MAX_VALUE - 10); break; case LoadOrderIndex0: // loadable but invalid metadata // location of order index default priority index size // so looks like there are no ids in the order index // picked up by setCheckForCorruptJournalFiles raf.seek(12 * 1024 + 21); raf.writeShort(0); raf.writeChar(0); raf.writeLong(-1); break; default: } raf.close(); // starting broker BrokerService broker = new BrokerService(); KahaDBStore kaha = new KahaDBStore(); kaha.setCheckForCorruptJournalFiles(failTest == CorruptionType.LoadOrderIndex0); // uncomment if you want to test archiving //kaha.setArchiveCorruptedIndex(true); kaha.setDirectory(new File(kahaDbDirectoryName)); broker.setPersistenceAdapter(kaha); return broker; }
From source file:mediathekplugin.Database.java
public ArrayList<MediathekProgramItem> getMediathekPrograms(final Program program) { ArrayList<MediathekProgramItem> result = new ArrayList<MediathekProgramItem>(); String channelName = unifyChannelName(program.getChannel().getName()); HashMap<Long, ArrayList<Integer>> programsMap = mChannelItems.get(channelName); // search parts in brackets like for ARD if (programsMap == null && channelName.contains("(")) { String bracketPart = StringUtils.substringBetween(channelName, "(", ")"); programsMap = mChannelItems.get(bracketPart); }// ww w. j a v a 2s .c o m // search for partial name, if full name is not found if (programsMap == null && channelName.contains(" ")) { String firstPart = StringUtils.substringBefore(channelName, " "); programsMap = mChannelItems.get(firstPart); } if (programsMap == null) { for (Entry<String, HashMap<Long, ArrayList<Integer>>> entry : mChannelItems.entrySet()) { if (StringUtils.startsWithIgnoreCase(channelName, entry.getKey())) { programsMap = entry.getValue(); break; } } } if (programsMap == null) { return result; } String title = program.getTitle(); ArrayList<Integer> programs = programsMap.get(getKey(title)); if (programs == null && title.endsWith(")") && title.contains("(")) { String newTitle = StringUtils.substringBeforeLast(title, "(").trim(); programs = programsMap.get(getKey(newTitle)); } if (programs == null && title.endsWith("...")) { String newTitle = title.substring(0, title.length() - 3).trim(); programs = programsMap.get(getKey(newTitle)); } if (programs == null) { return result; } try { RandomAccessFile file = new RandomAccessFile(new File(mFileName), "r"); for (Integer byteOffset : programs) { file.seek(byteOffset); String lineEncoded = file.readLine(); String line = new String(lineEncoded.getBytes(), "UTF-8"); Matcher itemMatcher = ITEM_PATTERN.matcher(line); if (itemMatcher.find()) { String itemTitle = itemMatcher.group(3).trim(); String itemUrl = itemMatcher.group(4).trim(); result.add(new MediathekProgramItem(itemTitle, itemUrl, null)); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }
From source file:org.openengsb.connector.promreport.internal.ProcessFileStore.java
private void writeTo(File proFile, ProcessInstance pi) { LOGGER.debug("write process instance {} to {}", pi.getId(), proFile.getName()); RandomAccessFile raf = null; try {/* ww w .j av a 2 s .c o m*/ raf = new RandomAccessFile(proFile, "rw"); long position = findLastProcess(raf); raf.seek(position); String s = marshal(pi); raf.writeBytes(s); raf.write(0x0A); raf.writeBytes(ENDDOC); } catch (Exception e) { throw new RuntimeException(e); } finally { try { raf.close(); } catch (IOException e) { } } }
From source file:de.micromata.genome.logging.spi.ifiles.IndexHeader.java
public String readSearchFromLog(Integer offset, RandomAccessFile file, String name) throws IOException { Integer fieldoffset = searchFieldsOffsets.get(name); if (fieldoffset == null) { return null; }/*from w w w.j av a2s. c om*/ file.seek(offset.intValue() + fieldoffset.intValue()); byte[] fieldBuffer = new byte[searchFieldsLength.get(name)]; file.readFully(fieldBuffer); String ret = new String(fieldBuffer); ret = ret.trim(); return ret; }