List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
From source file:com.tps.ttorrent.client.storage.FileStorage.java
/** Move the partial file to its final location. */// w w w. jav a 2 s . c om @Override public synchronized void finish() throws IOException { logger.debug("Closing file channel to " + this.current.getName() + " (download hasHeader)."); if (this.channel.isOpen()) { this.channel.force(true); } // Nothing more to do if we're already on the target file. if (this.isFinished()) { return; } this.raf.close(); FileUtils.deleteQuietly(this.target); FileUtils.moveFile(this.current, this.target); logger.debug("Re-opening torrent byte storage at {}.", this.target.getAbsolutePath()); this.raf = new RandomAccessFile(this.target, "rw"); this.raf.setLength(this.size); this.channel = this.raf.getChannel(); this.current = this.target; FileUtils.deleteQuietly(this.partial); logger.info("Moved torrent data from {} to {}.", this.partial.getName(), this.target.getName()); }
From source file:com.example.android.vault.EncryptedDocument.java
/** * Decrypt and return parsed metadata section from this document. * * @throws DigestException if metadata fails MAC check, or if * {@link Document#COLUMN_DOCUMENT_ID} recorded in metadata is * unexpected.// w ww .ja va 2 s . c o m */ public JSONObject readMetadata() throws IOException, GeneralSecurityException { final RandomAccessFile f = new RandomAccessFile(mFile, "r"); try { assertMagic(f); // Only interested in metadata section final ByteArrayOutputStream metaOut = new ByteArrayOutputStream(); readSection(f, metaOut); final String rawMeta = metaOut.toString(StandardCharsets.UTF_8.name()); if (DEBUG_METADATA) { Log.d(TAG, "Found metadata for " + mDocId + ": " + rawMeta); } final JSONObject meta = new JSONObject(rawMeta); // Validate that metadata belongs to requested file if (meta.getLong(Document.COLUMN_DOCUMENT_ID) != mDocId) { throw new DigestException("Unexpected document ID"); } return meta; } catch (JSONException e) { throw new IOException(e); } finally { f.close(); } }
From source file:gridool.dht.btree.Paged.java
protected final RandomAccessFile ensureResourceOpen() throws IndexException { if (_raf == null) { try {//from w w w . j av a 2 s. com this._raf = new RandomAccessFile(_file, "rw"); } catch (FileNotFoundException e) { throw new IndexException(e); } } if (_fc == null) { this._fc = _raf.getChannel(); } return _raf; }
From source file:com.qubole.rubix.core.CachingInputStream.java
private void initialize(FSDataInputStream parentInputStream, Configuration conf) { this.conf = conf; this.strictMode = CacheConfig.isStrictMode(conf); try {/*from w w w .ja v a 2 s .c om*/ this.bookKeeperClient = createBookKeeperClient(conf); } catch (Exception e) { if (strictMode) { throw Throwables.propagate(e); } log.warn("Could not create BookKeeper Client " + Throwables.getStackTraceAsString(e)); bookKeeperClient = null; } this.inputStream = checkNotNull(parentInputStream, "ParentInputStream is null"); this.blockSize = CacheConfig.getBlockSize(conf); this.localPath = CacheConfig.getLocalPath(remotePath, conf); try { this.localFileForReading = new RandomAccessFile(localPath, "r"); } catch (FileNotFoundException e) { log.info("Creating local file " + localPath); File file = new File(localPath); try { file.createNewFile(); this.localFileForReading = new RandomAccessFile(file, "rw"); } catch (IOException e1) { log.error("Error in creating local file " + localPath, e1); // reset bookkeeper client so that we take direct route this.bookKeeperClient = null; } } }
From source file:com.naryx.tagfusion.cfm.file.vfs.cfVFSData.java
public void openRandomAccessContent() throws IOException { if (fileObject != null) { randomAccessContent = fileObject.getContent().getRandomAccessContent(RandomAccessMode.READWRITE); randomAccessContent.seek(randomAccessContent.length()); } else {/*from w w w . java2 s .c om*/ randomAccessFile = new RandomAccessFile(file, "rw"); randomAccessFile.seek(randomAccessFile.length()); } }
From source file:com.microsoft.azure.management.datalake.store.uploader.UploadMetadataGeneratorTests.java
private void VerifySegmentsAreOnRecordBoundaries(UploadMetadata metadata, String filePath) throws IOException { try (RandomAccessFile stream = new RandomAccessFile(filePath, "r")) { for (UploadSegmentMetadata segment : metadata.getSegments()) { if (segment.getSegmentNumber() > 0) { //verify that each segment starts with a non-newline and that the 2 previous characters before that offset are newline characters //2 characters behind: newline // always seek from the file origin stream.seek(0);/*ww w . j av a2 s. co m*/ stream.seek(segment.getOffset() - 2); char c1 = (char) stream.read(); Assert.assertTrue( MessageFormat.format("Expecting a newline at offset {0}", segment.getOffset() - 2), IsNewline(c1)); //1 character behind: newline char c2 = (char) stream.read(); Assert.assertTrue( MessageFormat.format("Expecting a newline at offset {0}", segment.getOffset() - 2), IsNewline(c2)); //by test design, we never have two consecutive newlines that are the same; we'd always have \r\n, but never \r\r or \r\n char c3 = (char) stream.read(); Assert.assertNotEquals(c2, c3); } } } }
From source file:it.doqui.index.ecmengine.business.personalization.multirepository.FileContentWriterDynamic.java
@Override protected WritableByteChannel getDirectWritableChannel() throws ContentIOException { try {//from www.j av a 2 s. co m // we may not write to an existing file - EVER!! if (file.exists() && file.length() > 0) { throw new IOException("File exists - overwriting not allowed"); } // create the channel WritableByteChannel channel = null; if (allowRandomAccess) { RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); // will create it channel = randomAccessFile.getChannel(); } else { OutputStream os = new FileOutputStream(file); channel = Channels.newChannel(os); } // done if (logger.isDebugEnabled()) { logger.debug("Opened write channel to file: \n" + " file: " + file + "\n" + " random-access: " + allowRandomAccess); } return channel; } catch (Throwable e) { throw new ContentIOException("Failed to open file channel: " + this, e); } }
From source file:de.ailis.oneinstance.OneInstance.java
/** * Locks the specified lock file./*from w w w. j a v a 2s . c o m*/ * * @param lockFile * The lock file. * @return The lock or null if no locking could be performed. */ private FileLock lock(final File lockFile) { try { FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel(); return channel.lock(); } catch (IOException e) { LOG.warn("Unable to lock the lock file: " + e + ". Trying to run without a lock.", e); return null; } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * Deletes a newsdrilldown from the db.// ww w . j a va2 s .c o m * * @param entity The newsdrilldown to delete */ public void delete(UXBEntity entity) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); Query query = em.createQuery(new StringBuilder() .append("FROM news x WHERE x.fs_id = :fs_id AND x.language = :language").toString()); query.setParameter("fs_id", Long.parseLong(entity.getUuid())); query.setParameter("language", entity.getLanguage()); if (!query.getResultList().isEmpty()) { News art = (News) query.getSingleResult(); // delete file from filesystem URL url = new URL(art.getUrl()); File file = new File(webpath + url.getPath()); if (file.exists()) { // Try acquiring the lock without blocking. This method returns // null or throws an exception if the file is already locked. try { FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); // Try to lock the file FileLock lock = channel.tryLock(); // Delete the file file.delete(); // Release the lock lock.release(); lock.channel().close(); } catch (OverlappingFileLockException e) { logger.info("File is already locked in this thread or virtual machine"); } catch (MalformedURLException e) { logger.info("wrong url", e); } } // remove article from content repository em.remove(art); } tx.commit(); } catch (Exception e) { if (tx != null) { tx.setRollbackOnly(); } throw e; } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:com.github.rholder.esthree.command.Get.java
public MessageDigest retryingGet() throws ExecutionException, RetryException { return (MessageDigest) RetryUtils.AWS_RETRYER.call(new Callable<Object>() { public MessageDigest call() throws Exception { GetObjectRequest req = new GetObjectRequest(bucket, key); S3Object s3Object = amazonS3Client.getObject(req); contentLength = s3Object.getObjectMetadata().getContentLength(); fullETag = s3Object.getObjectMetadata().getETag(); Progress progress = new TransferProgressWrapper(new TransferProgress()); progress.setTotalBytesToTransfer(contentLength); if (progressListener != null) { progressListener.withTransferProgress(progress).withCompleted(0.0).withMultiplier(1.0); }//from ww w .j av a 2 s . co m InputStream input = null; try { // create the output file, now that we know it actually exists if (output == null) { output = new RandomAccessFile(outputFile, "rw"); } // seek to the start of the chunk in the file, just in case we're retrying output.seek(0); input = s3Object.getObjectContent(); return copyAndHash(input, contentLength, progress); } finally { IOUtils.closeQuietly(input); } } }); }