List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
From source file:com.slytechs.capture.FileFactory.java
public FormatType.Detail formatTypeDetail(final File file) throws IOException { try {//from w w w . j a va 2 s. com new PcapFileCapture(file, FileMode.ReadOnlyNoMap, null).close(); if (logger.isTraceEnabled()) { logger.trace(file.getName() + ", type=" + FormatType.Pcap); } return new DefaultFormatTypeDetail(FormatType.Pcap); } catch (final Exception e) { } try { new SnoopFileCapture(file, FileMode.ReadOnlyNoMap, null).close(); if (logger.isTraceEnabled()) { logger.trace(file.getName() + ", type=" + FormatType.Pcap); } return new DefaultFormatTypeDetail(FormatType.Snoop); } catch (final Exception e) { } /* * Now try InputCapture which may also yield a known format */ ReadableByteChannel channel = new RandomAccessFile(file, "r").getChannel(); FormatType.Detail detail = formatTypeDetail(channel); channel.close(); if (logger.isTraceEnabled()) { logger.trace(file.getName() + ", type=" + FormatType.Pcap + ", detail=" + detail); } return detail; }
From source file:com.btoddb.fastpersitentqueue.MemorySegmentSerializer.java
public boolean searchOffline(MemorySegment seg, FpqEntry target) throws IOException { RandomAccessFile raFile = new RandomAccessFile(createPagingFile(seg), "r"); try {/*from w w w. j a va 2 s .c om*/ // jump over header info - we already have it raFile.seek(seg.getEntryListOffsetOnDisk()); for (int i = 0; i < seg.getNumberOfEntries(); i++) { FpqEntry entry = new FpqEntry(); entry.readFromPaging(raFile); if (target.equals(entry)) { return true; } } return false; } finally { raFile.close(); } }
From source file:com.turn.ttorrent.client.TorrentByteStorage.java
/** Move the partial file to its final location. * * <p>//from www .j a va2s .c o m * This method needs to make sure reads can still happen seemlessly during * the operation. The partial is first flushed to the storage device before * being copied to its target location. The {@link FileChannel} is then * switched to this new file before the partial is removed. * </p> */ public synchronized void complete() throws IOException { this.channel.force(true); // Nothing more to do if we're already on the target file. if (this.current.equals(this.target)) { return; } FileUtils.deleteQuietly(this.target); FileUtils.copyFile(this.current, this.target); logger.debug("Re-opening torrent byte storage at " + this.target.getAbsolutePath() + "."); RandomAccessFile raf = new RandomAccessFile(this.target, "rw"); raf.setLength(this.size); this.channel = raf.getChannel(); this.raf.close(); this.raf = raf; this.current = this.target; FileUtils.deleteQuietly(this.partial); }
From source file:com.almende.eve.state.ConcurrentJsonFileState.java
/** * Open file.// ww w . j a v a 2s.com * * @throws IOException * Signals that an I/O exception has occurred. */ @SuppressWarnings("resource") protected void openFile() throws IOException { synchronized (locked) { while (locked.containsKey(filename) && locked.get(filename)) { try { locked.wait(); } catch (final InterruptedException e) { } } locked.put(filename, true); final File file = new File(filename); if (!file.exists()) { locked.put(filename, false); locked.notifyAll(); throw new IllegalStateException("Warning: File doesn't exist (anymore):'" + filename + "'"); } channel = new RandomAccessFile(file, "rw").getChannel(); try { // TODO: add support for shared locks, allowing parallel reading // operations. lock = channel.lock(); } catch (final Exception e) { channel.close(); channel = null; lock = null; locked.put(filename, false); locked.notifyAll(); throw new IllegalStateException("error, couldn't obtain file lock on:" + filename, e); } fis = Channels.newInputStream(channel); fos = Channels.newOutputStream(channel); } }
From source file:com.googlecode.download.maven.plugin.internal.DownloadCache.java
private void loadIndex() throws Exception { if (this.indexFile.isFile()) { try (FileLock lock = new RandomAccessFile(this.indexFile, "r").getChannel().lock(0, Long.MAX_VALUE, true)) {//from w w w .j ava 2s . co m try (ObjectInputStream deserialize = new ObjectInputStream(new FileInputStream(this.indexFile))) { this.index = (Map<String, CachedFileEntry>) deserialize.readObject(); } } } else { this.index = new HashMap<>(); } }
From source file:ch.cyberduck.core.io.FileBuffer.java
protected synchronized RandomAccessFile random() throws IOException { if (null == file) { try {/*from ww w . ja v a 2 s . c om*/ LocalTouchFactory.get().touch(temporary); } catch (AccessDeniedException e) { throw new IOException(e); } this.file = new RandomAccessFile(temporary.getAbsolute(), "rw"); this.file.seek(0L); } return file; }
From source file:jp.andeb.obbutil.ObbUtilMain.java
private static boolean doAdd(String[] args) { final CommandLine commandLine; try {//from ww w. java 2 s. co m final CommandLineParser parser = new GnuParser(); commandLine = parser.parse(OPTIONS_FOR_ADD, args); } catch (MissingArgumentException e) { System.err.println("??????: " + e.getOption().getOpt()); printUsage(PROGNAME); return false; } catch (MissingOptionException e) { System.err.println("??????: " + e.getMissingOptions()); printUsage(PROGNAME); return false; } catch (UnrecognizedOptionException e) { System.err.println("????: " + e.getOption()); printUsage(PROGNAME); return false; } catch (ParseException e) { System.err.println(e.getMessage()); printUsage(PROGNAME); return false; } final String pkgName = commandLine.getOptionValue(PACKAGE_NAME.getOpt()); final String versionStr = commandLine.getOptionValue(OBB_VERSION.getOpt()); final Integer version = toInteger(versionStr); if (version == null) { System.err.println("??????: " + versionStr); printUsage(PROGNAME); return false; } final boolean isOverlay = commandLine.hasOption(OVERLAY_FLAG.getOpt()); final String saltStr = commandLine.getOptionValue(SALT.getOpt()); final byte[] salt; if (saltStr == null) { salt = null; } else { salt = toByteArray(saltStr, ObbInfoV1.SALT_LENGTH); if (salt == null) { System.err.println("????: " + saltStr); printUsage(PROGNAME); return false; } } final String[] nonRecognizedArgs = commandLine.getArgs(); if (nonRecognizedArgs.length == 0) { System.err.println("????????"); printUsage(PROGNAME); return false; } if (nonRecognizedArgs.length != 1) { System.err.println("???????"); printUsage(PROGNAME); return false; } final File targetFile = new File(nonRecognizedArgs[0]); final RandomAccessFile targetRaFile; try { targetRaFile = new RandomAccessFile(targetFile, "rw"); } catch (FileNotFoundException e) { System.err.println("????: " + targetFile.getPath()); return false; } try { try { final ObbInfoV1 info = ObbInfoV1.fromFile(targetRaFile); System.err.println( "?? OBB ???????: " + info.toString()); return false; } catch (IOException e) { System.err .println("????????: " + targetFile.getPath()); return false; } catch (NotObbException e) { // } int flag = 0; if (isOverlay) { flag |= ObbInfoV1.FLAG_OVERLAY; } if (salt != null) { flag |= ObbInfoV1.FLAG_SALTED; } final ObbInfoV1 obbInfo = new ObbInfoV1(flag, salt, pkgName, version.intValue()); final ByteBuffer obbInfoBytes = obbInfo.toBytes(); // ??? targetRaFile.setLength(targetRaFile.length() + obbInfoBytes.remaining()); targetRaFile.seek(targetRaFile.length() - obbInfoBytes.remaining()); targetRaFile.write(obbInfoBytes.array(), obbInfoBytes.arrayOffset(), obbInfoBytes.remaining()); } catch (IOException e) { System.err.println("OBB ?????????: " + targetFile.getPath()); return false; } finally { try { targetRaFile.close(); } catch (IOException e) { System.err.println("OBB ?????????: " + targetFile.getPath()); return false; } } System.err.println("OBB ??????????: " + targetFile.getPath()); return true; }
From source file:it.tidalwave.northernwind.core.impl.util.CachedURIResolver.java
/******************************************************************************************************************* * ******************************************************************************************************************/ private void cacheDocument(final @Nonnull File cachedFile, final @Nonnull String href) throws IOException { log.debug(">>>> caching external document to {}", cachedFile); final File tempFile = File.createTempFile("temp", ".txt", new File(cacheFolderPath)); tempFile.deleteOnExit();// w ww . jav a 2 s.c o m log.debug(">>>> waiting for lock..."); try (final FileChannel channel = new RandomAccessFile(tempFile, "rw").getChannel(); final FileLock lock = channel.lock()) { log.debug(">>>> got lock: {}", lock); FileUtils.copyURLToFile(new URL(href), tempFile, connectionTimeout, readTimeout); rename(tempFile, cachedFile); } catch (IOException e) { if (cachedFile.exists()) { log.warn("Error while retrieving document from {}: {} - using previously cached file", href, e.toString()); } else { throw e; } } log.debug(">>>> done"); }
From source file:com.netease.qa.emmagee.utils.CpuInfo.java
/** * read stat of each CPU cores/*w w w . j a va 2s .c o m*/ */ private void readTotalCpuStat() { try { // monitor total and idle cpu stat of certain process RandomAccessFile cpuInfo = new RandomAccessFile(CPU_STAT, "r"); String line = ""; while ((null != (line = cpuInfo.readLine())) && line.startsWith("cpu")) { String[] toks = line.split("\\s+"); idleCpu.add(Long.parseLong(toks[4])); totalCpu.add(Long.parseLong(toks[1]) + Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[5]) + Long.parseLong(toks[7])); } cpuInfo.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.ettrema.zsync.UploadMakerEx.java
/** * Determines the byte ranges from the client file that need to be uploaded to the server. * //from www. jav a2 s . c o m * @param reverseMap The List of block-matches obtained from MakeContextEx * @param local The local file being uploaded * @param blockSize The block size used in reverseMap * @return An InputStream containing the dataStream portion of an Upload * @throws IOException * @throws UnsupportedEncodingException * @see UploadMaker#serversMissingRanges */ public static InputStream serversMissingRangesEx(List<OffsetPair> reverseMap, File local, int blockSize) throws UnsupportedEncodingException, IOException { ByteRangeWriter dataWriter = new ByteRangeWriter(16384); RandomAccessFile randAccess = null; Collections.sort(reverseMap, new OffsetPair.LocalSort()); reverseMap.add(new OffsetPair(local.length(), -1)); try { randAccess = new RandomAccessFile(local, "r"); long prevEnd = 0; for (OffsetPair pair : reverseMap) { long offset = pair.localOffset; if (offset - prevEnd > 0) { dataWriter.add(new Range(prevEnd, offset), randAccess); } prevEnd = offset + blockSize; } return dataWriter.getInputStream(); } finally { Util.close(randAccess); } }