List of usage examples for java.io RandomAccessFile read
public int read(byte b[], int off, int len) throws IOException
From source file:org.srlutils.Files.java
/** * wrapper for RandomAccessFile.read()// w w w . j a v a2 s. c o m * read len bytes from filename at position, filling bites starting at offset * if multiple exceptions are encountered (eg due to close() failing) throws the first only * @param bites if null, allocate a new array and read all available bytes * @param len if negative, fill bites * @return the byte array and number of bytes read * @throws RuntimeException wrapping any exceptions */ public static ReadInfo readbytes(String filename, long position, byte[] bites, int offset, int len) { ReadInfo read = new ReadInfo(); RandomAccessFile fid = null; RuntimeException rte = null; try { String mode = "r"; // fixme:memleak -- looks like fid is leaked ... fid = new RandomAccessFile(filename, mode); if (bites == null) { long size = fid.length() - position; if (size + offset > Integer.MAX_VALUE) throw new Exception(String.format( "attempt to read the entirity of file '%s', size %d, is too large", filename, len)); len = (int) size; bites = new byte[len + offset]; } if (len < 0) len = bites.length - offset; fid.seek(position); read.num = fid.read(bites, offset, len); read.bytes = bites; return read; } catch (Exception ex) { rte = rte(ex, "failed to read string from file: %s", filename); throw rte; } finally { if (rte == null) rteClose(fid); else tryClose(fid); } }
From source file:azkaban.common.utils.Utils.java
/** * Read in content of a file and get the last *lineCount* lines. It is * equivalent to *tail* command/*from w w w. j a v a 2s .co m*/ * * @param filename * @param lineCount * @param chunkSize * @return */ public static Vector<String> tail(String filename, int lineCount, int chunkSize) { try { // read in content of the file RandomAccessFile file = new RandomAccessFile(filename, "r"); // destination vector Vector<String> lastNLines = new Vector<String>(); // current position long currPos = file.length() - 1; long startPos; byte[] byteArray = new byte[chunkSize]; // read in content of the file in reverse order while (true) { // read in from *fromPos* startPos = currPos - chunkSize; if (startPos <= 0) { // toward the beginning of the file file.seek(0); file.read(byteArray, 0, (int) currPos); // only read in // curPos bytes parseLinesFromLast(byteArray, 0, (int) currPos, lineCount, lastNLines); break; } else { file.seek(startPos); if (byteArray == null) byteArray = new byte[chunkSize]; file.readFully(byteArray); if (parseLinesFromLast(byteArray, lineCount, lastNLines)) { break; // we got the last *lineCount* lines } // move the current position currPos = startPos; // + lastLine.getBytes().length; } } // there might be lineCount + 1 lines and the first line (now it is the last line) // might not be complete for (int index = lineCount; index < lastNLines.size(); index++) lastNLines.removeElementAt(index); // reverse the order of elements in lastNLines Collections.reverse(lastNLines); return lastNLines; } catch (Exception e) { return null; } }
From source file:org.coinspark.core.CSUtils.java
public static boolean readFromFileToBytes(RandomAccessFile aFile, byte[] raw) { int offset = 0; int bytesRead = 0; try {/*from ww w . j a va 2s.c o m*/ while ((offset < raw.length) && (bytesRead = aFile.read(raw, offset, raw.length - offset)) >= 0) { offset += bytesRead; } } catch (IOException ex) { return false; } return true; }
From source file:ch.cyberduck.core.io.FileBuffer.java
@Override public synchronized int read(final byte[] chunk, final Long offset) throws IOException { final RandomAccessFile file = random(); if (offset < file.length()) { file.seek(offset);// www . j a v a 2s. co m if (chunk.length + offset > file.length()) { return file.read(chunk, 0, (int) (file.length() - offset)); } else { return file.read(chunk, 0, chunk.length); } } else { final NullInputStream nullStream = new NullInputStream(length); if (nullStream.available() > 0) { nullStream.skip(offset); return nullStream.read(chunk, 0, chunk.length); } else { return IOUtils.EOF; } } }
From source file:com.microsoft.azure.management.datalake.store.uploader.UploadMetadataGenerator.java
/** * Reads data from the given file into the given buffer, centered around the given file offset. The first half of the buffer will be * filled with data right before the given offset, while the remainder of the buffer will contain data right after it (of course, containing the byte at the given offset). * @param stream The stream to read from * @param buffer The buffer to read data into * @param fileReferenceOffset The offset to start reading from in the stream. * @return The number of bytes reads, which could be less than the length of the input buffer if we can't read due to the beginning or the end of the file. * @throws IOException Thrown if the stream being used is invalid or inaccessible. *//* w w w .ja v a 2s. c o m*/ private static int readIntoBufferAroundReference(RandomAccessFile stream, byte[] buffer, long fileReferenceOffset) throws IOException { int length = buffer.length; //calculate start offset long fileStartOffset = fileReferenceOffset - length / 2; if (fileStartOffset < 0) { //offset is less than zero, adjust it, as well as the length we want to read length += (int) fileStartOffset; fileStartOffset = 0; if (length <= 0) { return 0; } } if (fileStartOffset + length > stream.length()) { //startOffset + length is beyond the end of the stream, adjust the length accordingly length = (int) (stream.length() - fileStartOffset); if (length <= 0) { return 0; } } //read the appropriate block of the file into the buffer, using symmetry with respect to its midpoint // we always initiate a seek from the origin of the file. stream.seek(0); stream.seek(fileStartOffset); int bufferOffset = 0; while (bufferOffset < length) { int bytesRead = stream.read(buffer, bufferOffset, length - bufferOffset); bufferOffset += bytesRead; } return length; }
From source file:fi.vtt.nubomedia.armodule.Ar3DHandler.java
private String getFile(String path) throws IOException { RandomAccessFile in = new RandomAccessFile(new File(path), "r"); FileChannel ch = in.getChannel(); long size = ch.size(); byte[] buf = new byte[(int) size]; in.read(buf, 0, buf.length); in.close();/*from w ww . j a v a2s.co m*/ return new String(buf); }
From source file:com.kkbox.toolkit.image.KKImageRequest.java
private void cryptToFile(String sourceFilePath, String targetFilePath) throws Exception { // FIXME: should have two functions: decyptToFile and encryptToFile RandomAccessFile sourceFile = new RandomAccessFile(sourceFilePath, "r"); RandomAccessFile targetFile = new RandomAccessFile(targetFilePath, "rw"); int readLength; do {//from w w w .j a v a2s.co m readLength = sourceFile.read(buffer, 0, BUFFER_SIZE); if (readLength != -1) { if (cipher != null) { buffer = cipher.doFinal(buffer); } targetFile.write(buffer, 0, readLength); } } while (readLength != -1); sourceFile.close(); targetFile.close(); }
From source file:ape.CorruptFileCommand.java
/** * This method is the actual method used to corrupt data/file */// ww w . j a v a2s . c om public boolean corrupt(String corruptAddress) throws IOException { FileInputStream fin; 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) { e.printStackTrace(); return false; } RandomAccessFile raf; try { raf = new RandomAccessFile(corruptAddress, "rw"); try { raf.seek(offset); raf.write(buf, 0, count); raf.seek(0); raf.close(); } catch (IOException e) { System.out.println("Corrupting file failed"); Main.logger.info("Corrupting file failed"); e.printStackTrace(); Main.logger.info(e); return false; } 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; } }
From source file:com.zimbra.cs.redolog.util.RedoLogVerify.java
public boolean scanLog(File logfile) throws IOException { boolean good = false; FileLogReader logReader = new FileLogReader(logfile, false); logReader.open();//from w w w .ja v a 2 s . c o m if (!mParams.quiet) { FileHeader header = logReader.getHeader(); mOut.println("HEADER"); mOut.println("------"); mOut.print(header); mOut.println("------"); } boolean hasMailboxIdsFilter = !mParams.mboxIds.isEmpty(); RedoableOp op = null; long lastPosition = 0; long lastOpStartOffset = 0; try { while ((op = logReader.getNextOp()) != null) { lastOpStartOffset = logReader.getLastOpStartOffset(); lastPosition = logReader.position(); if (hasMailboxIdsFilter) { int mboxId = op.getMailboxId(); if (op instanceof StoreIncomingBlob) { List<Integer> list = ((StoreIncomingBlob) op).getMailboxIdList(); if (list != null) { boolean match = false; for (Integer mid : list) { if (mParams.mboxIds.contains(mid)) { match = true; break; } } if (!match) continue; } // If list==null, it's a store incoming blob op targeted at unknown set of mailboxes. // It applies to our filtered mailboxes. } else if (!mParams.mboxIds.contains(mboxId)) { continue; } } if (!mParams.quiet) { printOp(mOut, op, mParams.hideOffset, lastOpStartOffset, lastPosition - lastOpStartOffset); if (mParams.showBlob) { InputStream dataStream = op.getAdditionalDataStream(); if (dataStream != null) { mOut.println("<START OF BLOB>"); ByteUtil.copy(dataStream, true, mOut, false); mOut.println(); mOut.println("<END OF BLOB>"); } } } } good = true; } catch (IOException e) { // The IOException could be a real I/O problem or it could mean // there was a server crash previously and there were half-written // log entries. mOut.println(); mOut.printf("Error while parsing data starting at offset 0x%08x", lastPosition); mOut.println(); long size = logReader.getSize(); long diff = size - lastPosition; mOut.printf("%d bytes remaining in the file", diff); mOut.println(); mOut.println(); if (op != null) { mOut.println("Last suceessfully parsed redo op:"); printOp(mOut, op, false, lastOpStartOffset, lastPosition - lastOpStartOffset); mOut.println(); } // hexdump data around the bad bytes int bytesPerLine = 16; int linesBefore = 10; int linesAfter = 10; long startPos = Math.max(lastPosition - (lastPosition % bytesPerLine) - linesBefore * bytesPerLine, 0); int count = (int) Math.min((linesBefore + linesAfter + 1) * bytesPerLine, lastPosition - startPos + diff); RandomAccessFile raf = null; try { raf = new RandomAccessFile(logfile, "r"); raf.seek(startPos); byte buf[] = new byte[count]; raf.read(buf, 0, count); mOut.printf("Data near error offset %08x:", lastPosition); mOut.println(); hexdump(mOut, buf, 0, count, startPos, lastPosition); mOut.println(); } catch (IOException eh) { mOut.println("Error opening log file " + logfile.getAbsolutePath() + " for hexdump"); eh.printStackTrace(mOut); } finally { if (raf != null) raf.close(); } throw e; } finally { logReader.close(); } return good; }
From source file:com.alibaba.otter.node.etl.common.pipe.impl.http.AbstractHttpPipe.java
protected void decodeFile(File file, String key, String crc) { // ??/*from w w w . j a v a 2s . com*/ RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "rw"); long totallength = file.length(); int keyLength = ByteUtils.stringToBytes(key).length; int crcLength = ByteUtils.stringToBytes(crc).length; // ? long pos = totallength - keyLength - crcLength; // raf.seek(pos); // ?key byte[] keyBytes = new byte[keyLength]; raf.read(keyBytes, 0, keyLength); String keystr = ByteUtils.bytesToString(keyBytes); if (!key.equals(keystr)) { throw new ChecksumException("unmatch garble key with[" + key + "],[" + keystr + "]"); } // ?? raf.seek(pos + keyLength); byte[] crcBytes = new byte[crcLength]; raf.read(crcBytes, 0, crcLength); String crcStr = ByteUtils.bytesToString(crcBytes); if (!crc.equals(crcStr)) { throw new ChecksumException("unmatch crc with[" + crc + "],[" + crcStr + "]"); } // raf.setLength(pos); } catch (Exception e) { throw new PipeException("read_encrypted_error", e); } finally { IOUtils.closeQuietly(raf); } }