List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
From source file:org.myframe.http.FileRequest.java
public byte[] handleResponse(HttpResponse response) throws IOException, KJHttpException { HttpEntity entity = response.getEntity(); long fileSize = entity.getContentLength(); if (fileSize <= 0) { MLoger.debug("Response doesn't present Content-Length!"); }// w w w. ja v a 2 s.c om long downloadedSize = mTemporaryFile.length(); boolean isSupportRange = HttpUtils.isSupportRange(response); if (isSupportRange) { fileSize += downloadedSize; String realRangeValue = HttpUtils.getHeader(response, "Content-Range"); if (!TextUtils.isEmpty(realRangeValue)) { String assumeRangeValue = "bytes " + downloadedSize + "-" + (fileSize - 1); if (TextUtils.indexOf(realRangeValue, assumeRangeValue) == -1) { throw new IllegalStateException("The Content-Range Header is invalid Assume[" + assumeRangeValue + "] vs Real[" + realRangeValue + "], " + "please remove the temporary file [" + mTemporaryFile + "]."); } } } if (fileSize > 0 && mStoreFile.length() == fileSize) { mStoreFile.renameTo(mTemporaryFile); mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, fileSize); return null; } RandomAccessFile tmpFileRaf = new RandomAccessFile(mTemporaryFile, "rw"); if (isSupportRange) { tmpFileRaf.seek(downloadedSize); } else { tmpFileRaf.setLength(0); downloadedSize = 0; } try { InputStream in = entity.getContent(); if (HttpUtils.isGzipContent(response) && !(in instanceof GZIPInputStream)) { in = new GZIPInputStream(in); } byte[] buffer = new byte[6 * 1024]; // 6K buffer int offset; while ((offset = in.read(buffer)) != -1) { tmpFileRaf.write(buffer, 0, offset); downloadedSize += offset; mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, downloadedSize); if (isCanceled()) { break; } } } finally { try { if (entity != null) entity.consumeContent(); } catch (Exception e) { MLoger.debug("Error occured when calling consumingContent"); } tmpFileRaf.close(); } return null; }
From source file:com.linkedin.pinot.core.index.writer.impl.FixedBitWidthRowColDataFileWriter.java
private void createBuffer(File file) throws FileNotFoundException, IOException { raf = new RandomAccessFile(file, "rw"); byteBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, 0, bytesRequired, file, this.getClass().getSimpleName() + " byteBuffer"); byteBuffer.position(0);//ww w . j a v a 2 s . com for (int i = 0; i < bytesRequired; i++) { byteBuffer.put((byte) 0); } }
From source file:com.almende.eve.state.file.ConcurrentSerializableFileState.java
/** * Open file.// w w w . j ava 2 s . co m * * @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 = new BufferedInputStream(Channels.newInputStream(channel)); fos = new BufferedOutputStream(Channels.newOutputStream(channel)); } }
From source file:com.turn.ttorrent.client.storage.FileStorage.java
/** Move the partial file to its final location. *//* ww w. jav a 2 s .c om*/ @Override public synchronized void finish() throws IOException { 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:bobs.is.compress.sevenzip.SevenZFile.java
/** * Reads a file as 7z archive//w w w . j a va 2s. c om * * @param filename the file to read * @param password optional password if the archive is encrypted - * the byte array is supposed to be the UTF16-LE encoded * representation of the password. * @throws IOException if reading the archive fails */ public SevenZFile(final File filename, final byte[] password) throws IOException { this.mapFilename = new HashMap(); boolean succeeded = false; this.file = new RandomAccessFile(filename, "r"); this.fileName = filename.getAbsolutePath(); try { archive = readHeaders(password); if (password != null) { this.password = new byte[password.length]; System.arraycopy(password, 0, this.password, 0, password.length); } else { this.password = null; } succeeded = true; } finally { if (!succeeded) { this.file.close(); } } }
From source file:hoot.services.info.ErrorLog.java
public String generateExportLog() throws Exception { String fileId = UUID.randomUUID().toString(); String outputPath = _tempOutputPath + "/" + fileId; String data = ""; AboutResource about = new AboutResource(); VersionInfo vInfo = about.getCoreVersionInfo(); data = "\n************ CORE VERSION INFO ***********\n"; data += vInfo.toString();//from w ww .j av a 2s .c om CoreDetail cd = about.getCoreVersionDetail(); data += "\n************ CORE ENVIRONMENT ***********\n"; if (cd != null) { data += StringUtils.join(cd.getEnvironmentInfo(), '\n'); } data = "\n************ SERVICE VERSION INFO ***********\n"; data += about.getServicesVersionInfo().toString(); ServicesDetail sd = about.getServicesVersionDetail(); if (sd != null) { data += "\n************ SERVICE DETAIL PROPERTY ***********\n"; for (ServicesDetail.Property prop : sd.getProperties()) { String str = prop.getName() + " : " + prop.getValue() + "\n"; data += str; } data += "\n************ SERVICE DETAIL RESOURCE ***********\n"; for (ServicesDetail.ServicesResource res : sd.getResources()) { String str = res.getType() + " : " + res.getUrl() + "\n"; data += str; } } data += "\n************ CATALINA LOG ***********\n"; // 5MB Max int maxSize = 5000000; String logStr = getErrorlog(maxSize); RandomAccessFile raf = new RandomAccessFile(outputPath, "rw"); raf.writeBytes(data + "\n" + logStr); raf.close(); return outputPath; }
From source file:com.aliyun.oss.integrationtests.TestUtils.java
public static String genFixedLengthFile(long fixedLength) throws IOException { ensureDirExist(TestBase.UPLOAD_DIR); String filePath = TestBase.UPLOAD_DIR + System.currentTimeMillis(); RandomAccessFile raf = new RandomAccessFile(filePath, "rw"); FileChannel fc = raf.getChannel(); MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, fixedLength); try {//from w w w . java 2 s .c om for (int i = 0; i < fixedLength; i++) { mbb.put(pickupAlphabet()); } return filePath; } finally { if (fc != null) { fc.close(); } if (raf != null) { raf.close(); } } }
From source file:ape.CorruptCommand.java
/** * This method is the implementation of the corrupt function. * Given an address, it corrupts the file in the given address */// www . jav a 2 s.com public boolean corrupt(String corruptAddress) throws IOException { // Trying to get a random HDFS block file if (Main.VERBOSE) { System.out.println("Trying to get a random HDFS block file"); } if (corruptAddress == null) { corruptAddress = getCorruptAddress(); } // If the above statement failed to set corruptAddress then there was a failure if (corruptAddress == null) { System.out.println("Could not get a random HDFS block file"); Main.logger.info("Could not get a random HDFS block file"); return false; } byte[] buf; int count; try { RandomAccessFile tmp = new RandomAccessFile(corruptAddress, "rw"); tmp.seek(offset); if (size <= 0) { System.out.println("ERROR: The size parameter must be positive"); Main.logger.info("ERROR: The size parameter must be positive"); return false; } buf = new byte[size]; count = 0; if ((count = tmp.read(buf, 0, size)) == -1) { System.out.println("The file chosen is smaller than the corruption size (" + size + " bytes)"); Main.logger.info("The file chosen is smaller than the corruption size (" + size + " bytes)"); return false; } for (int i = 0; i < count; i++) { buf[i] = 0x3; } tmp.seek(0); tmp.close(); } catch (FileNotFoundException e1) { System.out.println("Cannot open the file on the path given"); Main.logger.info("Cannot open the file on the path given"); e1.printStackTrace(); Main.logger.info(e1); return false; } catch (IOException e) { System.out.println("Corrupting file failed"); Main.logger.info("Corrupting file failed"); e.printStackTrace(); Main.logger.info(e); return false; } RandomAccessFile raf; try { raf = new RandomAccessFile(corruptAddress, "rw"); raf.seek(offset); raf.write(buf, 0, count); raf.seek(0); raf.close(); return true; } catch (FileNotFoundException e1) { System.out.println("Cannot open the file on the path: " + corruptAddress); Main.logger.info("Cannot open the file on the path: " + corruptAddress); e1.printStackTrace(); Main.logger.info(e1); return false; } catch (IOException e) { System.out.println("Corrupting file failed"); Main.logger.info("Corrupting file failed"); e.printStackTrace(); Main.logger.info(e); return false; } }
From source file:com.scut.easyfe.network.kjFrame.http.FileRequest.java
public byte[] handleResponse(HttpResponse response) throws IOException, KJHttpException { HttpEntity entity = response.getEntity(); long fileSize = entity.getContentLength(); if (fileSize <= 0) { KJLoger.debug("Response doesn't present Content-Length!"); }//ww w.j av a 2 s. c o m long downloadedSize = mTemporaryFile.length(); boolean isSupportRange = HttpUtils.isSupportRange(response); if (isSupportRange) { fileSize += downloadedSize; String realRangeValue = HttpUtils.getHeader(response, "Content-Range"); if (!TextUtils.isEmpty(realRangeValue)) { String assumeRangeValue = "bytes " + downloadedSize + "-" + (fileSize - 1); if (TextUtils.indexOf(realRangeValue, assumeRangeValue) == -1) { throw new IllegalStateException("The Content-Range Header is invalid Assume[" + assumeRangeValue + "] vs Real[" + realRangeValue + "], " + "please remove the temporary file [" + mTemporaryFile + "]."); } } } if (fileSize > 0 && mStoreFile.length() == fileSize) { mStoreFile.renameTo(mTemporaryFile); mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, fileSize); return null; } RandomAccessFile tmpFileRaf = new RandomAccessFile(mTemporaryFile, "rw"); if (isSupportRange) { tmpFileRaf.seek(downloadedSize); } else { tmpFileRaf.setLength(0); downloadedSize = 0; } try { InputStream in = entity.getContent(); if (HttpUtils.isGzipContent(response) && !(in instanceof GZIPInputStream)) { in = new GZIPInputStream(in); } byte[] buffer = new byte[6 * 1024]; // 6K buffer int offset; while ((offset = in.read(buffer)) != -1) { tmpFileRaf.write(buffer, 0, offset); downloadedSize += offset; mRequestQueue.getConfig().mDelivery.postDownloadProgress(this, fileSize, downloadedSize); if (isCanceled()) { break; } } } finally { try { if (entity != null) entity.consumeContent(); } catch (Exception e) { KJLoger.debug("Error occured when calling consumingContent"); } tmpFileRaf.close(); } return null; }
From source file:io.github.eternalbits.compactvd.CompactVD.java
private void copy(File from, int options, File to, String type) throws IOException { long mtime = to.lastModified(); task = DiskImageProgress.COPY;//from ww w. j a v a 2s . co m File copy = null; try (RandomAccessFile check = new RandomAccessFile(from, "r")) { // is file? // If writable, source is open in write mode for an exclusive file lock String mode = from.canWrite() ? "rw" : "r"; try (DiskImage image = DiskImages.open(from, mode)) { if (type == null) type = image.getType(); try (DiskImage clone = DiskImages.create(type, to, image.getDiskSize())) { copy = to; // copy open by DiskImage FileLock source = null; if (mode.equals("rw")) source = image.tryLock(); verboseProgress(SEARCHING_SPACE); image.addObserver(this, false); image.optimize(options); image.removeObserver(this); if (!isCancelled()) { verboseProgress("Copying " + from.getName() + " to " + to.getName()); FileLock fileLock = clone.tryLock(); clone.addObserver(this, false); clone.copy(image); clone.removeObserver(this); fileLock.release(); } if (source != null) source.release(); if (!isCancelled()) { copy = null; } } } } finally { if (copy != null && copy.isFile()) copy.delete(); System.out.println(mtime != to.lastModified() ? String.format(IMAGE_CREATED, to.getName(), to.getAbsoluteFile().getParent()) : IMAGE_NOT_CREATED); } }