List of usage examples for java.io RandomAccessFile seek
public void seek(long pos) throws IOException
From source file:com.android.volley.toolbox.UploadNetwork.java
@Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = Collections.emptyMap(); RandomAccessFile acessfile = null; File file = null;//from w w w. j a va 2 s .c o m try { if (!(request instanceof DownOrUpRequest)) { throw new IllegalArgumentException("request object mast be DownOrUpRequest???"); } DownOrUpRequest requestDown = (DownOrUpRequest) request; // Gather headers. Map<String, String> headers = new HashMap<String, String>(); // Download have no cache String url = requestDown.getUrl(); String name = url.substring(url.lastIndexOf('/'), url.length()); String path = requestDown.getDownloadPath(); String filePath = ""; if (path.endsWith("/")) { filePath = path + name; } else { path = path + "/"; filePath = path + "/" + name; } File dir = new File(path); dir.mkdirs(); file = File.createTempFile(path, null, dir); acessfile = new RandomAccessFile(file, "rws"); long length = acessfile.length(); acessfile.seek(length); // Range: bytes=5275648- headers.put("Range", "bytes=" + length + "-");// httpResponse = mHttpStack.performRequest(requestDown, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); // if the request is slow, log it. long requestLifetime = SystemClock.elapsedRealtime() - requestStart; logSlowRequests(requestLifetime, requestDown, responseContents, statusLine); if (statusCode < 200 || statusCode > 299) { acessfile.close(); throw new IOException(); } // Some responses such as 204s do not have content. We must check. if (httpResponse.getEntity() != null) { responseContents = entityToBytes(httpResponse.getEntity(), requestDown, acessfile); } else { // Add 0 byte response as a way of honestly representing a // no-content request. responseContents = new byte[0]; } acessfile.close(); file.renameTo(new File(filePath)); return new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { if (acessfile != null) { try { acessfile.close(); file.delete(); } catch (IOException e1) { e1.printStackTrace(); } } int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { throw new NoConnectionError(e); } VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); throw new NetworkError(networkResponse); } } }
From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetImpl.java
private static FileInputStream openAndSeek(File file, long offset) throws IOException { RandomAccessFile raf = null; try {//from w ww . j a va2 s . co m raf = new RandomAccessFile(file, "r"); if (offset > 0) { raf.seek(offset); } return new FileInputStream(raf.getFD()); } catch (IOException ioe) { IOUtils.cleanup(null, raf); throw ioe; } }
From source file:org.i_chera.wolfensteineditor.document.VSwapContainer.java
/** * Loads data from a file. Only finishes it on success * @param file the VSWAP.WL6 file to load * @return true on success//from w ww .j av a2s .c o m */ public boolean loadFile(File file) { RandomAccessFile raf = null; try { if (file.isDirectory()) return false; raf = new RandomAccessFile(file, "r"); int newNumChunks = FileUtil.readUInt16(raf); int newSpriteStart = FileUtil.readUInt16(raf); int newSoundStart = FileUtil.readUInt16(raf); int[] pageOffsets = new int[newNumChunks + 1]; for (int i = 0; i < newNumChunks; ++i) pageOffsets[i] = FileUtil.readInt32(raf); int[] pageLengths = new int[newNumChunks]; for (int i = 0; i < newNumChunks; ++i) pageLengths[i] = FileUtil.readUInt16(raf); pageOffsets[newNumChunks] = (int) file.length(); ArrayList<byte[]> newPages = new ArrayList<byte[]>(); byte[] reading; for (int i = 0; i < newNumChunks; ++i) { if (pageOffsets[i] == 0) { reading = new byte[0]; newPages.add(reading); continue; } int size; if (pageOffsets[i + 1] == 0) size = pageLengths[i]; else size = pageOffsets[i + 1] - pageOffsets[i]; raf.seek(pageOffsets[i]); reading = new byte[size]; raf.read(reading, 0, size); newPages.add(reading); } // okay mNumChunks = newNumChunks; mSpriteStart = newSpriteStart; mSoundStart = newSoundStart; mPages = newPages; } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); return false; } catch (IOException ioe) { ioe.printStackTrace(); return false; } finally { try { if (raf != null) raf.close(); } catch (IOException e) { e.printStackTrace(); } } return true; }
From source file:com.replaymod.replaystudio.launcher.ReverseLauncher.java
public void launch(CommandLine cmd) throws Exception { ZipFile file = new ZipFile(cmd.getArgs()[0]); ZipEntry entry = file.getEntry("recording.tmcpr"); if (entry == null) { throw new IOException("Input file is not a valid replay file."); }// w w w .j a v a 2 s . c o m long size = entry.getSize(); if (size == -1) { throw new IOException("Uncompressed size of recording.tmcpr not set."); } InputStream from = file.getInputStream(entry); RandomAccessFile to = new RandomAccessFile(cmd.getArgs()[1], "rw"); to.setLength(size); int nRead; long pos = size; byte[] buffer = new byte[8192]; long lastUpdate = -1; while (true) { long pct = 100 - pos * 100 / size; if (lastUpdate != pct) { System.out.print("Reversing " + size + " bytes... " + pct + "%\r"); lastUpdate = pct; } int next = readInt(from); int length = readInt(from); if (next == -1 || length == -1) { break; // reached end of stream } // Increase buffer if necessary if (length + 8 > buffer.length) { buffer = new byte[length + 8]; } buffer[0] = (byte) ((next >>> 24) & 0xFF); buffer[1] = (byte) ((next >>> 16) & 0xFF); buffer[2] = (byte) ((next >>> 8) & 0xFF); buffer[3] = (byte) (next & 0xFF); buffer[4] = (byte) ((length >>> 24) & 0xFF); buffer[5] = (byte) ((length >>> 16) & 0xFF); buffer[6] = (byte) ((length >>> 8) & 0xFF); buffer[7] = (byte) (length & 0xFF); nRead = 0; while (nRead < length) { nRead += from.read(buffer, 8 + nRead, length - nRead); } pos -= length + 8; to.seek(pos); to.write(buffer, 0, length + 8); } from.close(); to.close(); System.out.println("\nDone!"); }
From source file:com.polyvi.xface.extension.advancedfiletransfer.XFileDownloader.java
@Override public void transfer(XCallbackContext callbackCtx) { initDownloadInfo();// w w w . j av a 2 s .c o m if (mState == DOWNLOADING) { return; } mCallbackCtx = callbackCtx; if (null == mDownloadInfo) { onError(CONNECTION_ERR); } else { setState(DOWNLOADING); new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; RandomAccessFile randomAccessFile = null; InputStream is = null; int retry = RETRY; //TODO:????? do { int completeSize = mDownloadInfo.getCompleteSize(); try { URL url = new URL(mUrl); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(TIME_OUT_MILLISECOND); connection.setRequestMethod("GET"); // ?Rangebytes x-; connection.setRequestProperty("Range", "bytes=" + completeSize + "-"); //cookie setCookieProperty(connection, mUrl); // ?.temp randomAccessFile = new RandomAccessFile(mLocalFilePath + TEMP_FILE_SUFFIX, "rwd"); randomAccessFile.seek(completeSize); // ??? is = connection.getInputStream(); byte[] buffer = new byte[mBufferSize]; int length = -1; while ((length = is.read(buffer)) != -1) { try { randomAccessFile.write(buffer, 0, length); } catch (Exception e) { retry = -1; break; } completeSize += length; onProgressUpdated(completeSize, 0); if (PAUSE == mState) { break; } } if (mDownloadInfo.isDownloadCompleted()) { // ??.temp renameFile(mLocalFilePath + TEMP_FILE_SUFFIX, mLocalFilePath); onSuccess(); break; } } catch (IOException e) { if (retry <= 0) { onError(CONNECTION_ERR); XLog.e(CLASS_NAME, e.getMessage()); } // ,?1? try { Thread.sleep(RETRY_INTERVAL); } catch (InterruptedException ex) { XLog.e(CLASS_NAME, "sleep be interrupted", ex); } } finally { try { if (null != is) { is.close(); } if (null != randomAccessFile) { // new URL??randomAccessFilenull randomAccessFile.close(); } if (null != connection) { // new URL??connectionnull connection.disconnect(); } } catch (IOException e) { XLog.e(CLASS_NAME, e.getMessage()); } } } while ((DOWNLOADING == mState) && (0 < retry--)); } }).start(); } }
From source file:gate.util.reporting.PRTimeReporter.java
/** * Reads the given file upside down./*from w w w . j a va 2s . c o m*/ * * @param fileToBeRead * An object of type File representing the file to be read. * @param chunkSize * An integer specifying the size of the chunks in which file will be * read. * @return A long value pointing to the start position of the given file * chunk. * @throws BenchmarkReportInputFileFormatException */ private long tail(File fileToBeRead, int chunkSize) throws BenchmarkReportInputFileFormatException { RandomAccessFile raf = null; try { raf = new RandomAccessFile(fileToBeRead, "r"); Vector<String> lastNlines = new Vector<String>(); int delta = 0; long curPos = raf.length() - 1; long fromPos; byte[] bytearray; while (true) { fromPos = curPos - chunkSize; if (fromPos <= 0) { raf.seek(0); bytearray = new byte[(int) curPos]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines)) { if (fromPos < 0) fromPos = 0; } break; } else { raf.seek(fromPos); bytearray = new byte[chunkSize]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines)) { break; } delta = (lastNlines.get(lastNlines.size() - 1)).length(); lastNlines.remove(lastNlines.size() - 1); curPos = fromPos + delta; } } if (fromPos < 0) throw new BenchmarkReportInputFileFormatException( getBenchmarkFile().getAbsolutePath() + " does not contain a marker named " + getLogicalStart() + " indicating logical start of a run."); return fromPos; } catch (IOException e) { e.printStackTrace(); return -1; } finally { IOUtils.closeQuietly(raf); } }
From source file:org.apache.hadoop.hdfs.server.namenode.TestEditLog.java
/** * Test edit log failover from a corrupt edit log */// ww w . jav a 2s . c o m @Test public void testEditLogFailOverFromCorrupt() throws IOException { File f1 = new File(TEST_DIR + "/failover0"); File f2 = new File(TEST_DIR + "/failover1"); List<URI> editUris = ImmutableList.of(f1.toURI(), f2.toURI()); NNStorage storage = setupEdits(editUris, 3); final long startErrorTxId = 1 * TXNS_PER_ROLL + 1; final long endErrorTxId = 2 * TXNS_PER_ROLL; File[] files = new File(f1, "current").listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { if (name.startsWith(NNStorage.getFinalizedEditsFileName(startErrorTxId, endErrorTxId))) { return true; } return false; } }); assertEquals(1, files.length); long fileLen = files[0].length(); LOG.debug("Corrupting Log File: " + files[0] + " len: " + fileLen); RandomAccessFile rwf = new RandomAccessFile(files[0], "rw"); rwf.seek(fileLen - 4); // seek to checksum bytes int b = rwf.readInt(); rwf.seek(fileLen - 4); rwf.writeInt(b + 1); rwf.close(); FSEditLog editlog = getFSEditLog(storage); editlog.initJournalsForWrite(); long startTxId = 1; Collection<EditLogInputStream> streams = null; try { streams = editlog.selectInputStreams(startTxId, 4 * TXNS_PER_ROLL); readAllEdits(streams, startTxId); } catch (IOException e) { LOG.error("edit log failover didn't work", e); fail("Edit log failover didn't work"); } finally { IOUtils.cleanup(null, streams.toArray(new EditLogInputStream[0])); } }
From source file:org.apache.hadoop.hdfs.server.namenode.TestEditLog.java
@Test public void testEditChecksum() throws Exception { // start a cluster Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = null;/*w w w.j a v a 2 s .c o m*/ FileSystem fileSys = null; cluster = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DATA_NODES).build(); cluster.waitActive(); fileSys = cluster.getFileSystem(); final FSNamesystem namesystem = cluster.getNamesystem(); FSImage fsimage = namesystem.getFSImage(); final FSEditLog editLog = fsimage.getEditLog(); fileSys.mkdirs(new Path("/tmp")); Iterator<StorageDirectory> iter = fsimage.getStorage().dirIterator(NameNodeDirType.EDITS); LinkedList<StorageDirectory> sds = new LinkedList<StorageDirectory>(); while (iter.hasNext()) { sds.add(iter.next()); } editLog.close(); cluster.shutdown(); for (StorageDirectory sd : sds) { File editFile = NNStorage.getFinalizedEditsFile(sd, 1, 3); assertTrue(editFile.exists()); long fileLen = editFile.length(); LOG.debug("Corrupting Log File: " + editFile + " len: " + fileLen); RandomAccessFile rwf = new RandomAccessFile(editFile, "rw"); rwf.seek(fileLen - 4); // seek to checksum bytes int b = rwf.readInt(); rwf.seek(fileLen - 4); rwf.writeInt(b + 1); rwf.close(); } try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DATA_NODES).format(false).build(); fail("should not be able to start"); } catch (IOException e) { // expected assertNotNull("Cause of exception should be ChecksumException", e.getCause()); assertEquals("Cause of exception should be ChecksumException", ChecksumException.class, e.getCause().getClass()); } }
From source file:com.polyvi.xface.extension.advancedfiletransfer.FileDownloader.java
@Override public void transfer(CallbackContext callbackCtx) { initDownloadInfo();/*from w ww . j av a 2 s. c om*/ if (mState == DOWNLOADING) { return; } mCallbackCtx = callbackCtx; if (null == mDownloadInfo) { onError(CONNECTION_ERR); } else { setState(DOWNLOADING); new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; RandomAccessFile randomAccessFile = null; InputStream is = null; int retry = RETRY; // TODO:????? do { int completeSize = mDownloadInfo.getCompleteSize(); try { URL url = new URL(mUrl); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(TIME_OUT_MILLISECOND); connection.setRequestMethod("GET"); // ?Rangebytes x-; connection.setRequestProperty("Range", "bytes=" + completeSize + "-"); // cookie setCookieProperty(connection, mUrl); // ?.temp randomAccessFile = new RandomAccessFile(mLocalFilePath + TEMP_FILE_SUFFIX, "rwd"); randomAccessFile.seek(completeSize); // ??? is = connection.getInputStream(); byte[] buffer = new byte[mBufferSize]; int length = -1; while ((length = is.read(buffer)) != -1) { try { randomAccessFile.write(buffer, 0, length); } catch (Exception e) { retry = -1; break; } completeSize += length; onProgressUpdated(completeSize, mDownloadInfo.getTotalSize()); mDownloadInfo.setCompleteSize(completeSize); if (PAUSE == mState) { break; } } if (mDownloadInfo.isDownloadCompleted()) { // ??.temp renameFile(mLocalFilePath + TEMP_FILE_SUFFIX, mLocalFilePath); onSuccess(); break; } } catch (FileNotFoundException e) { onError(FILE_NOT_FOUND_ERR); XLog.e(CLASS_NAME, e.getMessage()); } catch (IOException e) { if (retry <= 0) { onError(CONNECTION_ERR); XLog.e(CLASS_NAME, e.getMessage()); } // ,?1? try { Thread.sleep(RETRY_INTERVAL); } catch (InterruptedException ex) { XLog.e(CLASS_NAME, "sleep be interrupted", ex); } } finally { try { if (null != is) { is.close(); } if (null != randomAccessFile) { // new URL??randomAccessFilenull randomAccessFile.close(); } if (null != connection) { // new URL??connectionnull connection.disconnect(); } } catch (IOException e) { XLog.e(CLASS_NAME, e.getMessage()); } } } while ((DOWNLOADING == mState) && (0 < retry--)); } }).start(); } }
From source file:dbseer.comp.process.live.LogTailer.java
/** * Read new lines./*from w w w . ja v a2s.co m*/ * * @param reader The file to read * @return The new position after the lines have been read * @throws java.io.IOException if an I/O error occurs. */ private long readLines(RandomAccessFile reader) throws IOException { StringBuilder sb = new StringBuilder(); long pos = reader.getFilePointer(); long rePos = pos; // position to re-read int num; boolean seenCR = false; while (run && ((num = reader.read(inbuf)) != -1)) { for (int i = 0; i < num; i++) { byte ch = inbuf[i]; switch (ch) { case '\n': seenCR = false; // swallow CR before LF listener.handle(sb.toString(), pos + i + 1); sb.setLength(0); rePos = pos + i + 1; break; case '\r': if (seenCR) { sb.append('\r'); } seenCR = true; break; default: if (seenCR) { seenCR = false; // swallow final CR listener.handle(sb.toString(), pos + i + 1); sb.setLength(0); rePos = pos + i + 1; } sb.append((char) ch); // add character, not its ascii value } } pos = reader.getFilePointer(); } reader.seek(rePos); // Ensure we can re-read if necessary return rePos; }