List of usage examples for java.io RandomAccessFile seek
public void seek(long pos) throws IOException
From source file:com.dotmarketing.servlets.taillog.Tailer.java
/** * Read new lines.// w ww .j av a 2s . c o 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 { long pos = reader.getFilePointer(); String line = readLine(reader); while (line != null) { pos = reader.getFilePointer(); listener.handle(line); line = readLine(reader); } reader.seek(pos); // Ensure we can re-read if necessary return pos; }
From source file:com.haulmont.cuba.core.sys.LogControlImpl.java
@Override public String getTail(String fileName) throws LogControlException { // security check, supported only valid file names fileName = FilenameUtils.getName(fileName); StringBuilder sb = new StringBuilder(); RandomAccessFile randomAccessFile = null; try {/* ww w.jav a 2s . c om*/ File logFile = new File(logDir, fileName); if (!logFile.exists()) throw new LogFileNotFoundException(fileName); randomAccessFile = new RandomAccessFile(logFile, "r"); long lengthFile = randomAccessFile.length(); if (lengthFile >= LOG_TAIL_AMOUNT_BYTES) { randomAccessFile.seek(lengthFile - LOG_TAIL_AMOUNT_BYTES); skipFirstLine(randomAccessFile); } while (randomAccessFile.read() != -1) { randomAccessFile.seek(randomAccessFile.getFilePointer() - 1); String line = readUtf8Line(randomAccessFile); if (line != null) { sb.append(line).append("\n"); } } } catch (IOException e) { log.error("Error reading log file", e); throw new LogControlException("Error reading log file: " + fileName); } finally { if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException ignored) { } } } return sb.toString(); }
From source file:com.example.android.vault.EncryptedDocument.java
/** * Encrypt and write both the metadata and content sections of this * document, reading the content from the given pipe. Internally uses * {@link ParcelFileDescriptor#checkError()} to verify that content arrives * without errors. Writes to temporary file to keep atomic view of contents, * swapping into place only when write is successful. * <p/>//from w w w . j ava2 s. c o m * Pipe is left open, so caller is responsible for calling * {@link ParcelFileDescriptor#close()} or * {@link ParcelFileDescriptor#closeWithError(String)}. * * @param contentIn read end of a pipe. */ public void writeMetadataAndContent(JSONObject meta, ParcelFileDescriptor contentIn) throws IOException, GeneralSecurityException { // Write into temporary file to provide an atomic view of existing // contents during write, and also to recover from failed writes. final String tempName = mFile.getName() + ".tmp_" + Thread.currentThread().getId(); final File tempFile = new File(mFile.getParentFile(), tempName); RandomAccessFile f = new RandomAccessFile(tempFile, "rw"); try { // Truncate any existing data f.setLength(0); // Write content first to detect size if (contentIn != null) { f.seek(CONTENT_OFFSET); final int plainLength = writeSection(f, new FileInputStream(contentIn.getFileDescriptor())); meta.put(Document.COLUMN_SIZE, plainLength); // Verify that remote side of pipe finished okay; if they // crashed or indicated an error then this throws and we // leave the original file intact and clean up temp below. contentIn.checkError(); } meta.put(Document.COLUMN_DOCUMENT_ID, mDocId); meta.put(Document.COLUMN_LAST_MODIFIED, System.currentTimeMillis()); // Rewind and write metadata section f.seek(0); f.writeInt(MAGIC_NUMBER); final ByteArrayInputStream metaIn = new ByteArrayInputStream( meta.toString().getBytes(StandardCharsets.UTF_8)); writeSection(f, metaIn); if (f.getFilePointer() > CONTENT_OFFSET) { throw new IOException("Metadata section was too large"); } // Everything written fine, atomically swap new data into place. // fsync() before close would be overkill, since rename() is an // atomic barrier. f.close(); tempFile.renameTo(mFile); } catch (JSONException e) { throw new IOException(e); } finally { // Regardless of what happens, always try cleaning up. f.close(); tempFile.delete(); } }
From source file:com.aol.advertising.qiao.injector.file.AbstractFileReader.java
protected long checksum(RandomAccessFile raFile) throws IOException, IllegalStateException { long pos = raFile.getFilePointer(); try {/* ww w. j av a2s . c o m*/ byte[] buffer = new byte[checksumByteLength]; raFile.seek(0); int n = raFile.read(buffer); if (n < checksumByteLength) { String s; logger.warn(s = ("not enough data for checksum: current file size=" + n)); throw new IllegalStateException(s); } synchronized (_crc) { _crc.reset(); _crc.update(buffer); return _crc.getValue(); } } finally { raFile.seek(pos); } }
From source file:com.example.android.vault.EncryptedDocument.java
/** * Decrypt and read content section of this document, writing it into the * given pipe.// w ww .j a v a 2s .co m * <p/> * Pipe is left open, so caller is responsible for calling * {@link ParcelFileDescriptor#close()} or * {@link ParcelFileDescriptor#closeWithError(String)}. * * @param contentOut write end of a pipe. * @throws DigestException if content fails MAC check. Some or all content * may have already been written to the pipe when the MAC is * validated. */ public void readContent(ParcelFileDescriptor contentOut) throws IOException, GeneralSecurityException { final RandomAccessFile f = new RandomAccessFile(mFile, "r"); try { assertMagic(f); if (f.length() <= CONTENT_OFFSET) { throw new IOException("Document has no content"); } // Skip over metadata section f.seek(CONTENT_OFFSET); readSection(f, new FileOutputStream(contentOut.getFileDescriptor())); } finally { f.close(); } }
From source file:org.pentaho.platform.web.servlet.UploadFileUtils.java
/** * Gets the uncompressed file size of a .gz file by reading the last four bytes of the file * /* w w w . j av a 2 s .c om*/ * @param file * @return long uncompressed original file size * @throws IOException * mbatchelor */ private long getUncompressedGZipFileSize(File file) throws IOException { long rtn = 0; RandomAccessFile gzipFile = new RandomAccessFile(file, "r"); try { // go 4 bytes from end of file - the original uncompressed file size is there gzipFile.seek(gzipFile.length() - 4); byte[] intelSize = new byte[4]; gzipFile.read(intelSize); // read the size .... // rfc1952; ISIZE is the input size modulo 2^32 // 00F01E69 is really 691EF000 // The &0xFF turns signed byte into unsigned. rtn = (((intelSize[3] & 0xFF) << 24) | ((intelSize[2] & 0xFF) << 16) + ((intelSize[1] & 0xFF) << 8) + (intelSize[0] & 0xFF)) & 0xffffffffL; } finally { try { gzipFile.close(); } catch (Exception ignored) { //ignored } } return rtn; }
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 {// w w w . ja v a 2 s . c o 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:org.ngrinder.perftest.service.AgentManager.java
@Override public synchronized AgentUpdateGrinderMessage onAgentDownloadRequested(String version, int offset) { final int updateChunkSize = getUpdateChunkSize(); byte[] buffer = new byte[updateChunkSize]; RandomAccessFile agentPackageReader = null; try {/*from w w w .j a v a2 s .com*/ agentPackageReader = new RandomAccessFile(agentPackageService.createAgentPackage(), "r"); agentPackageReader.seek(offset); int count = agentPackageReader.read(buffer, 0, updateChunkSize); byte[] bytes = buffer; int next = offset + count; if (count != updateChunkSize) { bytes = Arrays.copyOf(buffer, count); next = 0; } return new AgentUpdateGrinderMessage(version, bytes, offset, next, CRC32ChecksumUtils.getCRC32Checksum(bytes)); } catch (Exception e) { LOGGER.error("Error while reading agent package, its offset is {} and details {}:", offset, e); } finally { IOUtils.closeQuietly(agentPackageReader); } return AgentUpdateGrinderMessage.getNullAgentUpdateGrinderMessage(version); }
From source file:com.frand.easyandroid.http.FFFileRespHandler.java
public int copy(InputStream input, RandomAccessFile out) throws IOException { interrupt = false;// w ww . j av a 2 s .c o m 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:org.xwalk.runtime.extension.api.device_capabilities.DeviceCapabilitiesCPU.java
/** * The algorithm here can be found at://from w w w . j a v a 2s .c om * http://stackoverflow.com/questions/3017162/how-to-get-total-cpu-usage-in-linux-c */ private boolean getCPULoad() { try { RandomAccessFile file = new RandomAccessFile(SYSTEM_INFO_STAT_FILE, "r"); String line = file.readLine(); String[] arrs = line.split("\\s+"); long total1 = 0; for (int i = 1; i < arrs.length; ++i) { total1 += Long.parseLong(arrs[i]); } // arrs[4] is the time spent in idle tasks. long used1 = total1 - Long.parseLong(arrs[4]); try { Thread.sleep(1000); } catch (Exception e) { mCPULoad = 0.0; return false; } file.seek(0); line = file.readLine(); file.close(); arrs = line.split("\\s+"); long total2 = 0; for (int i = 1; i < arrs.length; ++i) { total2 += Long.parseLong(arrs[i]); } // arrs[4] is the time spent in idle tasks. long used2 = total2 - Long.parseLong(arrs[4]); if (total2 == total1) { mCPULoad = 0.0; } else { mCPULoad = (double) (used2 - used1) / (total2 - total1); } } catch (IOException e) { mCPULoad = 0.0; return false; } return true; }