List of usage examples for java.io RandomAccessFile write
public void write(byte b[], int off, int len) throws IOException
From source file:jp.andeb.obbutil.ObbUtilMain.java
private static boolean doAdd(String[] args) { final CommandLine commandLine; try {//from ww w. j av a 2 s . c om 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:org.commoncrawl.service.listcrawler.CacheWriterThread.java
@Override public void run() { boolean shutdown = false; while (!shutdown) { try {//w ww . j av a2s .co m final CacheWriteRequest request = _writeRequestQueue.take(); switch (request._requestType) { case ExitThreadRequest: { // shutdown condition ... CacheManager.LOG.info("Disk Writer Thread Received Shutdown. Exiting!"); shutdown = true; } break; case WriteRequest: { long timeStart = System.currentTimeMillis(); try { // reset crc calculator (single thread so no worries on synchronization) _crc32Out.reset(); // figure out if we need to compress the item ... if ((request._item.getFlags() & CacheItem.Flags.Flag_IsCompressed) == 0 && request._item.getContent().getCount() != 0) { LOG.info("Incoming Cache Request Content for:" + request._item.getUrl() + " is not compressed. Compressing..."); ByteStream compressedBytesOut = new ByteStream(request._item.getContent().getCount()); ThriftyGZIPOutputStream gzipOutputStream = new ThriftyGZIPOutputStream( compressedBytesOut); gzipOutputStream.write(request._item.getContent().getReadOnlyBytes(), 0, request._item.getContent().getCount()); gzipOutputStream.finish(); LOG.info("Finished Compressing Incoming Content for:" + request._item.getUrl() + " BytesIn:" + request._item.getContent().getCount() + " BytesOut:" + compressedBytesOut.size()); // replace buffer request._item.setContent( new FlexBuffer(compressedBytesOut.getBuffer(), 0, compressedBytesOut.size())); request._item.setFlags((request._item.getFlags() | CacheItem.Flags.Flag_IsCompressed)); } // create streams ... ByteStream bufferOutputStream = new ByteStream(8192); CheckedOutputStream checkedStream = new CheckedOutputStream(bufferOutputStream, _crc32Out); DataOutputStream dataOutputStream = new DataOutputStream(checkedStream); // remember if this item has content ... boolean hasContent = request._item.isFieldDirty(CacheItem.Field_CONTENT); // now mark the content field as clean, so that it will not be serialized in our current serialization attempt ... request._item.setFieldClean(CacheItem.Field_CONTENT); // and go ahead and write out the data to the intermediate buffer while also computing partial checksum request._item.write(dataOutputStream); request._item.setFieldDirty(CacheItem.Field_CONTENT); // ok, now ... write out file header ... CacheItemHeader itemHeader = new CacheItemHeader(_manager.getLocalLogSyncBytes()); itemHeader._status = CacheItemHeader.STATUS_ALIVE; itemHeader._lastAccessTime = System.currentTimeMillis(); itemHeader._fingerprint = request._itemFingerprint; // compute total length ... // first the header bytes in the cacheItem itemHeader._dataLength = bufferOutputStream.size(); // next the content length (encoded - as in size + bytes) ... itemHeader._dataLength += 4 + request._item.getContent().getCount(); // lastly the crc value iteself ... itemHeader._dataLength += 8; // open the log file ... DataOutputBuffer logStream = new DataOutputBuffer(); // ok, go ahead and write the header itemHeader.writeHeader(logStream); // ok now write out the item data minus content... logStream.write(bufferOutputStream.getBuffer(), 0, bufferOutputStream.size()); // now create a checked stream for the content ... CheckedOutputStream checkedStream2 = new CheckedOutputStream(logStream, checkedStream.getChecksum()); dataOutputStream = new DataOutputStream(checkedStream2); // content size dataOutputStream.writeInt(request._item.getContent().getCount()); // now write out the content (via checked stream so that we can calc checksum on content) dataOutputStream.write(request._item.getContent().getReadOnlyBytes(), 0, request._item.getContent().getCount()); // ok ... lastly write out the checksum bytes ... dataOutputStream.writeLong(checkedStream2.getChecksum().getValue()); // and FINALLY, write out the total item bytes (so that we can seek in reverse to read last request log logStream.writeInt(CacheItemHeader.SIZE + itemHeader._dataLength); // ok flush everyting to the memory stream dataOutputStream.flush(); //ok - time to acquire the log semaphore //LOG.info("Acquiring Local Log Semaphore"); _manager.getLocalLogAccessSemaphore().acquireUninterruptibly(); try { // now time to acquire the write semaphore ... _manager.getLocalLogWriteAccessSemaphore().acquireUninterruptibly(); // get the current file position long recordOffset = _manager.getLocalLogFilePos(); try { long ioTimeStart = System.currentTimeMillis(); RandomAccessFile logFile = new RandomAccessFile(_manager.getActiveLogFilePath(), "rw"); try { // seek to our known record offset logFile.seek(recordOffset); // write out the data logFile.write(logStream.getData(), 0, logStream.getLength()); } finally { logFile.close(); } // now we need to update the file header _manager.updateLogFileHeader(_manager.getActiveLogFilePath(), 1, CacheItemHeader.SIZE + itemHeader._dataLength + 4 /*trailing bytes*/); CacheManager.LOG .info("#### Wrote Cache Item in:" + (System.currentTimeMillis() - timeStart) + " iotime:" + (System.currentTimeMillis() - ioTimeStart) + " QueueSize:" + _writeRequestQueue.size()); } finally { // release write semaphore quickly _manager.getLocalLogWriteAccessSemaphore().release(); } // now inform the manager of the completed request ... _manager.writeRequestComplete(request, recordOffset); } finally { //LOG.info("Releasing Local Log Semaphore"); _manager.getLocalLogAccessSemaphore().release(); } } catch (IOException e) { CacheManager.LOG.error("### FUC# BATMAN! - GONNA LOSE THIS REQUEST!!!!:" + CCStringUtils.stringifyException(e)); _manager.writeRequestFailed(request, e); } } break; } } catch (InterruptedException e) { } } }
From source file:com.kkbox.toolkit.image.KKImageRequest.java
@Override public Bitmap doInBackground(Object... params) { Bitmap bitmap;/* w ww. j a v a 2 s.c om*/ try { int readLength; cachePath = KKImageManager.getTempImagePath(context, url); File cacheFile = new File(cachePath); File localFile = null; String tempFilePath = context.getCacheDir().getAbsolutePath() + File.separator + "image" + File.separator + hashCode(); if (localPath != null) { localFile = new File(localPath); } try { if (cacheFile.exists()) { if (actionType == KKImageManager.ActionType.DOWNLOAD) { if (localFile == null || !localFile.exists()) { cryptToFile(cachePath, localPath); } return null; } else { bitmap = decodeBitmap(cachePath); if (bitmap != null) { if (localPath != null && saveToLocal && (localFile == null || !localFile.exists())) { cryptToFile(cachePath, localPath); } return bitmap; } else { removeCacheFile(); } } } if (localFile != null && localFile.exists()) { if (actionType == KKImageManager.ActionType.DOWNLOAD) { return null; } else { cryptToFile(localPath, tempFilePath); moveFileTo(tempFilePath, cachePath); bitmap = decodeBitmap(cachePath); if (bitmap != null) { return bitmap; } else { removeCacheFile(); } } } } catch (Exception e) { } // Do fetch server resource if either cache nor local file is not valid to read if (!KKImageManager.networkEnabled) { return null; } final HttpGet httpget = new HttpGet(url); response = httpclient.execute(httpget); final InputStream is = response.getEntity().getContent(); headers = response.getAllHeaders(); removeInvalidImageFiles(); if (actionType == KKImageManager.ActionType.DOWNLOAD) { RandomAccessFile tempFile = new RandomAccessFile(tempFilePath, "rw"); while ((readLength = is.read(buffer, 0, buffer.length)) != -1) { if (interuptFlag) { return null; } if (cipher != null) { buffer = cipher.doFinal(buffer); } tempFile.write(buffer, 0, readLength); } tempFile.close(); moveFileTo(tempFilePath, localPath); return null; } else { RandomAccessFile tempFile; try { tempFile = new RandomAccessFile(tempFilePath, "rw"); } catch (IOException e) { // we don't save to SD card if cache is full return BitmapFactory.decodeStream(is); } try { while ((readLength = is.read(buffer, 0, buffer.length)) != -1) { if (interuptFlag) { return null; } tempFile.write(buffer, 0, readLength); } } catch (IOException e) { tempFile.close(); return null; } tempFile.close(); moveFileTo(tempFilePath, cachePath); bitmap = decodeBitmap(cachePath); if (bitmap != null) { if (saveToLocal && localPath != null) { cryptToFile(cachePath, localPath); } return bitmap; } } } catch (final Exception e) { isNetworkError = true; removeInvalidImageFiles(); } return null; }
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!"); }/* ww w. j a va 2s .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) { MLoger.debug("Error occured when calling consumingContent"); } tmpFileRaf.close(); } return null; }
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!"); }//from w ww . j a v a2 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) { KJLoger.debug("Error occured when calling consumingContent"); } tmpFileRaf.close(); } return null; }
From source file:FastByteArrayOutputStream.java
public void writeTo(RandomAccessFile out) throws IOException { // Check if we have a list of buffers if (buffers != null) { Iterator iter = buffers.iterator(); while (iter.hasNext()) { byte[] bytes = (byte[]) iter.next(); out.write(bytes, 0, blockSize); }// w ww . java 2s. c o m } // write the internal buffer directly out.write(buffer, 0, index); }
From source file:com.csipsimple.service.DownloadLibService.java
private boolean installRemoteLib(RemoteLibInfo lib) { String fileName = lib.getFileName(); File filePath = lib.getFilePath(); File tmp_gz = new File(filePath, fileName + ".gz"); File dest = new File(filePath, fileName); try {//from www . j av a 2s . co m if (dest.exists()) { dest.delete(); } RandomAccessFile out = new RandomAccessFile(dest, "rw"); out.seek(0); GZIPInputStream zis = new GZIPInputStream(new FileInputStream(tmp_gz)); int len; byte[] buf = new byte[BUFFER]; while ((len = zis.read(buf)) > 0) { out.write(buf, 0, len); } zis.close(); out.close(); Log.d(THIS_FILE, "Ungzip is in : " + dest.getAbsolutePath()); tmp_gz.delete(); //Update preferences fields with current stack values Editor editor = prefs.edit(); editor.putString(CURRENT_STACK_ID, lib.getId()); editor.putString(CURRENT_STACK_VERSION, lib.getVersion()); editor.putString(CURRENT_STACK_URI, lib.getDownloadUri().toString()); editor.commit(); return true; } catch (IOException e) { Log.e(THIS_FILE, "We failed to install it ", e); } return false; }
From source file:com.android.volley.toolbox.UploadNetwork.java
/** Reads the contents of HttpEntity into a byte[]. * @param request //from w w w . jav a 2 s . c o m * @param acessfile */ private byte[] entityToBytes(HttpEntity entity, DownOrUpRequest request, RandomAccessFile acessfile) throws IOException, ServerError { // PoolingByteArrayOutputStream bytes = // new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength()); long length = acessfile.length(); request.setmMaxLength(entity.getContentLength()); byte[] buffer = new byte[1024]; try { InputStream in = entity.getContent(); if (in == null) { throw new ServerError(); } int count; while ((count = in.read(buffer)) != -1) { if (request.isCanceled()) { break; } acessfile.write(buffer, 0, count); length += count; request.doProcess(length); } return null; } finally { try { // Close the InputStream and release the resources by "consuming the content". entity.consumeContent(); } catch (IOException e) { // This can happen if there was an exception above that left the entity in // an invalid state. VolleyLog.v("Error occured when calling consumingContent"); } // bytes.close(); } }
From source file:com.frand.easyandroid.http.FFFileRespHandler.java
public int copy(InputStream input, RandomAccessFile out) throws IOException { interrupt = false;/*from www .jav a 2 s. c om*/ if (input == null || out == null) { return -1; } byte[] buffer = new byte[BUFFER_SIZE]; BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE); int count = 0, n = 0; long errorBlockTimePreviousTime = -1, expireTime = 0; try { out.seek(out.length()); previousTime = System.currentTimeMillis(); while (!interrupt) { n = in.read(buffer, 0, BUFFER_SIZE); if (n == -1) { break; } out.write(buffer, 0, n); count += n; if (networkSpeed == 0) { if (errorBlockTimePreviousTime > 0) { expireTime = System.currentTimeMillis() - errorBlockTimePreviousTime; if (expireTime > TIME_OUT) { throw new ConnectTimeoutException("connection time out."); } } else { errorBlockTimePreviousTime = System.currentTimeMillis(); } } else { expireTime = 0; errorBlockTimePreviousTime = -1; } } } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } return count; }
From source file:com.android.volley.toolbox.DownloadNetwork.java
/** Reads the contents of HttpEntity into a byte[]. * @param request /*from www . j av a 2 s .com*/ * @param acessfile */ private byte[] entityToBytes(HttpEntity entity, DownOrUpRequest request, RandomAccessFile acessfile) throws IOException, ServerError { // PoolingByteArrayOutputStream bytes = // new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength()); long length = acessfile.length(); request.setmMaxLength(entity.getContentLength() + length); byte[] buffer = new byte[1024]; try { InputStream in = entity.getContent(); if (in == null) { throw new ServerError(); } int count; while ((count = in.read(buffer)) != -1) { if (request.isCanceled()) { break; } acessfile.write(buffer, 0, count); length += count; request.doProcess(length); } return null; } finally { try { // Close the InputStream and release the resources by "consuming the content". entity.consumeContent(); } catch (IOException e) { // This can happen if there was an exception above that left the entity in // an invalid state. VolleyLog.v("Error occured when calling consumingContent"); } // bytes.close(); } }