Bitmap loadBitmap(RandomAccessFile file) { try { byte imgBytes[] = new byte[102400]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int nRead = file.read(imgBytes); while (nRead > 0) { baos.write(imgBytes); nRead = file.read(imgBytes); } file.close(); byte[] imgBuff = baos.toByteArray(); Bitmap orgImage = BitmapFactory.decodeByteArray(imgBuff, 0, imgBuff.length); baos.close(); return orgImage; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
/** * Returns the uncompressed size of the file in a quick, but unreliable manner. It will not * report the correct size if: * * <ol> * <li>The compressed size is larger than 2<sup>32</sup> bytes. * <li>The file is broken or truncated. * <li>The file has not been generated by a standard-conformant compressor. * <li>It is a multi-volume GZIP stream. * </ol> * * <p>The advantage of this approach is, that it only reads the first 2 and last 4 bytes of the * target file. If the first 2 bytes are not the GZIP magic number, the raw length of the file * is returned. * * @see #isGzipStream(File) * @param file * @return the size of the uncompressed file content. */ public static long getGzipStreamSize(File file) { if (!isGzipStream(file)) { return file.length(); } RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "r"); if (raf.length() <= 4) { raf.close(); return file.length(); } raf.seek(raf.length() - 4); int b4 = raf.read(); int b3 = raf.read(); int b2 = raf.read(); int b1 = raf.read(); return (b1 << 24) + (b2 << 16) + (b3 << 8) + b4; } catch (IOException ex) { return file.length(); } finally { if (raf != null) try { raf.close(); } catch (IOException e) { // ignore } } }
/** * Copy the given byte range of the given input to the given output. * * @param input The input to copy the given range to the given output for. * @param output The output to copy the given range from the given input for. * @param start Start of the byte range. * @param length Length of the byte range. * @throws IOException If something fails at I/O level. */ private static void copy(RandomAccessFile input, OutputStream output, long start, long length) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int read; if (input.length() == length) { // Write full range. while ((read = input.read(buffer)) > 0) { output.write(buffer, 0, read); } } else { // Write partial range. input.seek(start); long toRead = length; while ((read = input.read(buffer)) > 0) { if ((toRead -= read) > 0) { output.write(buffer, 0, read); } else { output.write(buffer, 0, (int) toRead + read); break; } } } }
public static String readLine(RandomAccessFile file, Charset cs) throws IOException { ByteArrayOutputStream lineBytes = new ByteArrayOutputStream(); int b = -1; boolean eol = false; while (!eol) { switch (b = file.read()) { case -1: case '\n': eol = true; break; case '\r': eol = true; long cur = file.getFilePointer(); if ((file.read()) != '\n') { file.seek(cur); } break; default: lineBytes.write(b); break; } } byte[] bytes = lineBytes.toByteArray(); if (b == -1) { return null; } return new String(bytes, cs); }
/** * Read a file offset from the file PST Files have this tendency to store file offsets (pointers) * in 8 little endian bytes. Convert this to a long for seeking to. * * @param in handle for PST file * @param startOffset where to read the 8 bytes from * @return long representing the read location * @throws IOException */ protected long extractLEFileOffset(long startOffset) throws IOException { long offset = 0; if (this.getPSTFileType() == PSTFile.PST_TYPE_ANSI) { in.seek(startOffset); byte[] temp = new byte[4]; in.read(temp); offset |= temp[3] & 0xff; offset <<= 8; offset |= temp[2] & 0xff; offset <<= 8; offset |= temp[1] & 0xff; offset <<= 8; offset |= temp[0] & 0xff; } else { in.seek(startOffset); byte[] temp = new byte[8]; in.read(temp); offset = temp[7] & 0xff; long tmpLongValue; for (int x = 6; x >= 0; x--) { offset = offset << 8; tmpLongValue = (long) temp[x] & 0xff; offset |= tmpLongValue; } } return offset; }
public boolean add_song_from_file(String a_file_path) { RandomAccessFile m_file = null; try { m_file = new RandomAccessFile(a_file_path, "r"); byte l_file_name[] = new byte[8]; m_file.read(l_file_name); byte l_file_version = m_file.readByte(); byte l_buffer[] = new byte[0x8000 * 4]; int l_bytes_read = m_file.read(l_buffer); int l_blocks_read = l_bytes_read / g_block_size; if (l_blocks_read > get_free_blocks() || !has_free_slot()) { return false; } byte l_free_slot = get_free_slot(); int l_file_name_ptr = g_file_name_start_ptr + l_free_slot * g_file_name_length; m_work_ram[l_file_name_ptr++] = l_file_name[0]; m_work_ram[l_file_name_ptr++] = l_file_name[1]; m_work_ram[l_file_name_ptr++] = l_file_name[2]; m_work_ram[l_file_name_ptr++] = l_file_name[3]; m_work_ram[l_file_name_ptr++] = l_file_name[4]; m_work_ram[l_file_name_ptr++] = l_file_name[5]; m_work_ram[l_file_name_ptr++] = l_file_name[6]; m_work_ram[l_file_name_ptr++] = l_file_name[7]; int l_file_version_ptr = g_file_version_start_ptr + l_free_slot; m_work_ram[l_file_version_ptr] = l_file_version; int l_blocks_to_write = l_blocks_read; int l_buffer_index = 0; int l_next_block_id_ptr = 0; while (l_blocks_to_write-- > 0) { int l_block_id = get_block_id_of_first_free_block(); if (0 != l_next_block_id_ptr) { // add one to compensate for unused FAT block m_work_ram[l_next_block_id_ptr] = (byte) (l_block_id + 1); } m_work_ram[g_block_alloc_table_start_ptr + l_block_id] = l_free_slot; int l_block_ptr = g_block_start_ptr + l_block_id * g_block_size; for (int l_byte = 0; l_byte < g_block_size; l_byte++) { m_work_ram[l_block_ptr++] = l_buffer[l_buffer_index++]; } l_next_block_id_ptr = get_next_block_id_ptr(l_block_id); } m_file.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
private void loadDataXM(RandomAccessFile fp) throws IOException { byte[] b = new byte[20]; // WHY THE HELL AM I DOING THIS name = Util.readStringNoNul(fp, b, 20); System.out.printf("name: \"%s\"\n", name); fp.read(); // skip 0x1A byte // THIS CAN'T BE HAPPENING fp.read(b, 0, 20); // skip tracker name // OH HELL NO int xmver = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); System.out.printf("XM version: %04X\n", xmver); // WHAT IS THIS CRAP InhibitedFileBlock ifb = new InhibitedFileBlock(fp, Integer.reverseBytes(fp.readInt()) - 4); // HELP ME PLEASE int ordnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); int respos = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); // can't be bothered right now --GM int chnnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); // yeah sure, allow out of range values if (chnnum > 64) throw new RuntimeException( String.format("%d-channel modules not supported (max 64)", chnnum)); int patnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); int insnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); int xmflags = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); int xmspeed = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); int xmtempo = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); // OH PLEASE, STOP IT if (ordnum > 255) ordnum = 255; if (xmtempo > 255) xmtempo = 255; if (xmspeed > 255) xmspeed = 255; this.bpm = xmtempo; this.spd = xmspeed; this.flags = FLAG_COMPATGXX | FLAG_OLDEFFECTS | FLAG_INSMODE | FLAG_STEREO | FLAG_VOL0MIX; if ((xmflags & 0x01) != 0) this.flags |= FLAG_LINEAR; // NONONONONONO System.out.printf("chn=%d ordnum=%d tempo=%d speed=%s\n", chnnum, ordnum, xmtempo, xmspeed); for (int i = 0; i < 256; i++) orderlist[i] = ifb.read(); for (int i = ordnum; i < 256; i++) orderlist[i] = 255; ifb.done(); // SAVE ME PLEEEEEAAASSSSEEEE for (int i = 0; i < patnum; i++) map_pat.put((Integer) i, new SessionPattern(this, fp, SessionPattern.FORMAT_XM, chnnum)); for (int i = 0; i < insnum; i++) map_ins.put((Integer) (i + 1), new SessionInstrument(fp, SessionInstrument.FORMAT_XM, this)); }
/** * Returns the uncompressed size for a Gzipped file. * * @param file Gzipped file to get the size for * @return Size when uncompressed, in bytes * @throws IOException */ private int getGzipSizeUncompressed(File zipFile) throws IOException { RandomAccessFile raf = new RandomAccessFile(zipFile, "r"); raf.seek(raf.length() - 4); int b4 = raf.read(); int b3 = raf.read(); int b2 = raf.read(); int b1 = raf.read(); raf.close(); return (b1 << 24) | (b2 << 16) + (b3 << 8) + b4; }
/* * gets an (uncompressed) stream representing the chunk data returns null if * the chunk is not found or an error occurs */ public synchronized DataInputStream getChunkDataInputStream(int x, int z) { if (outOfBounds(x, z)) { debugln("READ", x, z, "out of bounds"); return null; } try { int offset = getOffset(x, z); if (offset == 0) { // debugln("READ", x, z, "miss"); return null; } int sectorNumber = offset >> 8; int numSectors = offset & 0xFF; if (sectorNumber + numSectors > sectorFree.size()) { debugln("READ", x, z, "invalid sector"); return null; } file.seek(sectorNumber * SECTOR_BYTES); int length = file.readInt(); if (length > SECTOR_BYTES * numSectors) { debugln("READ", x, z, "invalid length: " + length + " > 4096 * " + numSectors); return null; } byte version = file.readByte(); if (version == VERSION_GZIP) { byte[] data = new byte[length - 1]; file.read(data); DataInputStream ret = new DataInputStream( new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data)))); // debug("READ", x, z, " = found"); return ret; } else if (version == VERSION_DEFLATE) { byte[] data = new byte[length - 1]; file.read(data); DataInputStream ret = new DataInputStream( new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data)))); // debug("READ", x, z, " = found"); return ret; } debugln("READ", x, z, "unknown version " + version); return null; } catch (IOException e) { debugln("READ", x, z, "exception"); return null; } }
private void parse(String path, long len) throws IOException { ByteBuffer byteBuffer; long sum = 0, newlen = 0; byte[] buffer = new byte[8]; String name = ""; if (!path.equals("")) mBoxes.put(path, mPos - 8); while (sum < len) { mFile.read(buffer, 0, 8); mPos += 8; sum += 8; if (validBoxName(buffer)) { name = new String(buffer, 4, 4); if (buffer[3] == 1) { // 64 bits atom size mFile.read(buffer, 0, 8); mPos += 8; sum += 8; byteBuffer = ByteBuffer.wrap(buffer, 0, 8); newlen = byteBuffer.getLong() - 16; } else { // 32 bits atom size byteBuffer = ByteBuffer.wrap(buffer, 0, 4); newlen = byteBuffer.getInt() - 8; } // 1061109559+8 correspond to "????" in ASCII the HTC Desire S seems to write that // sometimes, maybe other phones do // "wide" atom would produce a newlen == 0, and we shouldn't throw an exception because of // that if (newlen < 0 || newlen == 1061109559) throw new IOException(); Log.d(TAG, "Atom -> name: " + name + " position: " + mPos + ", length: " + newlen); sum += newlen; parse(path + '/' + name, newlen); } else { if (len < 8) { mFile.seek(mFile.getFilePointer() - 8 + len); sum += len - 8; } else { int skipped = mFile.skipBytes((int) (len - 8)); if (skipped < ((int) (len - 8))) { throw new IOException(); } mPos += len - 8; sum += len - 8; } } } }
/** * Given a zip File input it will return its size Only works for zip files whose uncompressed size * is less than 4 GB, otherwise returns the size module 2^32, per gzip specifications * * @param myFile The zip file as input * @throws IOException * @return zip file size as a long */ public static long zipFileSize(File myFile) throws IOException { RandomAccessFile raf = new RandomAccessFile(myFile, "r"); raf.seek(raf.length() - 4); long b4 = raf.read(); long b3 = raf.read(); long b2 = raf.read(); long b1 = raf.read(); long val = (b1 << 24) | (b2 << 16) + (b3 << 8) + b4; raf.close(); return val; }
/** * Gets if the file is compressed with gzip. * * @param file * @return gzip */ private static boolean isGzip(File file) { try { RandomAccessFile raf = new RandomAccessFile(file, "r"); int magic = raf.read() & 0xff | (raf.read() << 8) & 0xff00; raf.close(); return magic == GZIPInputStream.GZIP_MAGIC; } catch (Exception e) { e.printStackTrace(); } return false; }
/** * The Vorbis Comment may span multiple pages so we we need to identify the pages they contain and * then extract the packet data from the pages * * @param startVorbisCommentPage * @param raf * @return * @throws org.jaudiotagger.audio.exceptions.CannotReadException * @throws java.io.IOException */ private byte[] convertToVorbisCommentPacket( OggPageHeader startVorbisCommentPage, RandomAccessFile raf) throws IOException, CannotReadException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte [startVorbisCommentPage.getPacketList().get(0).getLength() - (VorbisHeader.FIELD_PACKET_TYPE_LENGTH + VorbisHeader.FIELD_CAPTURE_PATTERN_LENGTH)]; raf.read(b); baos.write(b); // Because there is at least one other packet (SetupHeaderPacket) this means the Comment Packet // has finished // on this page so thats all we need and we can return if (startVorbisCommentPage.getPacketList().size() > 1) { // //logger.info("Comments finish on 2nd Page because there is another packet on // this page"); return baos.toByteArray(); } // There is only the VorbisComment packet on page if it has completed on this page we can return if (!startVorbisCommentPage.isLastPacketIncomplete()) { // //logger.info("Comments finish on 2nd Page because this packet is complete"); return baos.toByteArray(); } // The VorbisComment extends to the next page, so should be at end of page already // so carry on reading pages until we get to the end of comment while (true) { // //logger.info("Reading next page"); OggPageHeader nextPageHeader = OggPageHeader.read(raf); b = new byte[nextPageHeader.getPacketList().get(0).getLength()]; raf.read(b); baos.write(b); // Because there is at least one other packet (SetupHeaderPacket) this means the Comment // Packet has finished // on this page so thats all we need and we can return if (nextPageHeader.getPacketList().size() > 1) { // //logger.info("Comments finish on Page because there is another packet on // this page"); return baos.toByteArray(); } // There is only the VorbisComment packet on page if it has completed on this page we can // return if (!nextPageHeader.isLastPacketIncomplete()) { // //logger.info("Comments finish on Page because this packet is complete"); return baos.toByteArray(); } } }
// TODO Implementation pending public Bucket readBucketFromFile(String path, Long offset, String datatype) { // If offset is -1 , return null // Since the bucket cannot be read. if (offset == -1) return null; RandomAccessFile raf; Bucket temp = new Bucket(this.maxSize, (long) -1); byte[] tempData = new byte[4]; byte[] tempOffsetAddress = new byte[8]; long tempOffset = 0; Comparer comparer = new Comparer(); try { raf = new RandomAccessFile(new File(path), "rw"); raf.seek(offset); raf.read(tempData); temp.maxSize = Helper.toInt(tempData); raf.read(tempData); temp.currentSize = Helper.toInt(tempData); raf.read(tempData); temp.numberOfOverflowBuckets = Helper.toInt(tempData); raf.read(tempOffsetAddress); temp.overflowOffset = Helper.toLong(tempOffsetAddress); tempOffset = raf.getFilePointer(); raf.close(); for (int i = 0; i < this.maxSize; i++) { if (datatype.contains("c")) { temp.data[i][0] = comparer.compare_functions[6].readString( path, (int) tempOffset, Integer.parseInt(datatype.substring(1))); } else temp.data[i][0] = comparer.compare_functions[comparer.mapper.indexOf(datatype)].readString( path, (int) tempOffset, Integer.parseInt(datatype.substring(1))); tempOffset += Integer.parseInt(datatype.substring(1)); temp.data[i][1] = comparer.compare_functions[3].readString(path, (int) tempOffset, 8); tempOffset += 8; } return temp; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
private boolean findBoxAvcc() { try { fis.seek(pos + 8); while (true) { while (fis.read() != 'a') ; fis.read(buffer, 0, 3); if (buffer[0] == 'v' && buffer[1] == 'c' && buffer[2] == 'C') break; } } catch (IOException e) { return false; } return true; }
private boolean findSPSandPPS() { /* * SPS and PPS parameters are stored in the avcC box * You may find really useful information about this box * in the document ISO-IEC 14496-15, part 5.2.4.1.1 * The box's structure is described there * * aligned(8) class AVCDecoderConfigurationRecord { * unsigned int(8) configurationVersion = 1; * unsigned int(8) AVCProfileIndication; * unsigned int(8) profile_compatibility; * unsigned int(8) AVCLevelIndication; * bit(6) reserved = ‘111111’b; * unsigned int(2) lengthSizeMinusOne; * bit(3) reserved = ‘111’b; * unsigned int(5) numOfSequenceParameterSets; * for (i=0; i< numOfSequenceParameterSets; i++) { * unsigned int(16) sequenceParameterSetLength ; * bit(8*sequenceParameterSetLength) sequenceParameterSetNALUnit; * } * unsigned int(8) numOfPictureParameterSets; * for (i=0; i< numOfPictureParameterSets; i++) { * unsigned int(16) pictureParameterSetLength; * bit(8*pictureParameterSetLength) pictureParameterSetNALUnit; * } * } * * * */ try { // TODO: Here we assume that numOfSequenceParameterSets = 1, numOfPictureParameterSets = 1 ! // Here we extract the SPS parameter fis.skipBytes(7); spsLength = 0xFF & fis.readByte(); sps = new byte[spsLength]; fis.read(sps, 0, spsLength); // Here we extract the PPS parameter fis.skipBytes(2); ppsLength = 0xFF & fis.readByte(); pps = new byte[ppsLength]; fis.read(pps, 0, ppsLength); } catch (IOException e) { return false; } return true; }
/* * (non-Javadoc) * * @see java.nio.channels.SeekableByteChannel#read(java.nio.ByteBuffer) */ @Override public int read(ByteBuffer dst) throws IOException { if (dst == null) { throw new NullPointerException("The destination buffer is null."); } if (dst.limit() == 0) { throw new IllegalArgumentException("The destination buffer has zero length."); } if (!_open) return -1; // Make an attempt to read up to r bytes from the channel, where // r is the number of bytes remaining in the buffer, that is, // dst.remaining(), at the moment this method is invoked. long _here = position(); // Build temporary storage. int remain = dst.remaining(); byte[] data = new byte[remain]; int length = _backing.read(data, 0, remain); if (length > 0) { // Iterate thru each byte of temporary storage and decrypt those // bytes back // into the buffer for (int index = 0; index < length; index++) { data[index] = _head.crypt(data[index], index + _here); } // Decrypt all bytes. dst.put(data, 0, length); } return length; }
/** * 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. */ 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; }
@Override public int read(ByteBuffer bb) throws IOException { int c = raf.read(bb.array(), bb.position(), bb.remaining()); if (c == -1) return -1; bb.position(bb.position() + c); return c; }
public int luaCB_read(Lua l, LuaPlugin plugin) { l.pushNil(); l.pushNil(); try { long offset = (long) l.checkNumber(2); int length = (int) l.checkNumber(3); if (length <= 0) { l.pushNil(); l.pushString("Length is not positive"); return 2; } byte[] tmp = new byte[length]; object.seek(offset); length = object.read(tmp); if (length < 0) { l.pushNil(); l.pushNil(); return 2; } StringBuffer buf = new StringBuffer(length); for (byte x : tmp) buf.appendCodePoint((int) x & 0xFF); l.push(buf.toString()); } catch (IOException e) { l.pushNil(); l.pushString("IOException: " + e.getMessage()); return 2; } return 1; }
/** @return A {@link Yes1Reader}, {@link Yes2Reader}, or null if there is any error. */ public static BibleReader createYesReader(String filename) { try { RandomAccessFile f = new RandomAccessFile(filename, "r"); byte[] header = new byte[8]; f.read(header); if (header[0] != (byte) 0x98 || header[1] != (byte) 0x58 || header[2] != (byte) 0x0d || header[3] != (byte) 0x0a || header[4] != (byte) 0x00 || header[5] != (byte) 0x5d || header[6] != (byte) 0xe0) { Log.e(TAG, "Yes file has not a correct header. Header is: " + Arrays.toString(header)); return null; } if (header[7] == 0x01) { // VERSION 1 YES return new Yes1Reader(f); } else if (header[7] == 0x02) { // VERSION 2 YES return new Yes2Reader(new RandomAccessFileRandomInputStream(f)); } else { Log.e(TAG, "Yes file version unsupported: " + header[7]); return null; } } catch (IOException e) { Log.e(TAG, "@@createYesReader io exception", e); return null; } }
/** * reads the content of an existing file using the current domain * * @param domain The namespace used to identify the application domain (1st level directory) to * use * @param path The path relative to the domain for the file * @param offset the offset from the beginning of the file. * @param len The length of the block in bytes * @return The contents of the file */ public byte[] readByteFromFile(String path, long offset, int len) throws EOFException, FileAccessException { try { if (_isLocal) { File tmpFile = new File(_rootFile.getCanonicalPath() + File.separatorChar + path); if (tmpFile.isFile()) { RandomAccessFile raf = new RandomAccessFile(tmpFile, "r"); byte[] buffer = new byte[len]; raf.seek(offset); int totalByteRead = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); int result = 0; while (totalByteRead < len && raf.getFilePointer() < raf.length()) { result = raf.read(buffer, 0, (len - totalByteRead)); if (result != -1) { out.write(buffer, 0, result); totalByteRead += result; } else if (totalByteRead == 0) throw new EOFException("End of file reached!"); else break; } raf.close(); out.flush(); out.close(); return out.toByteArray(); } else throw new FileAccessException("Path is not a file"); } else return _remote.readByteFromFile(_domain, path, offset, len); } catch (EOFException eofe) { throw eofe; } catch (FileAccessException fae) { throw fae; } catch (Exception e) { throw new FileAccessException(e); } }
/** * reads the content of an existing file using the current domain * * @param domain The namespace used to identify the application domain (1st level directory) to * use * @param path The path relative to the domain for the file * @param block The sequential block number for the data to be read starting with 1 * @param len The length of the block in bytes * @return The contents of the file */ public byte[] readFromFile(String path, int block, int len) { byte[] buffer = null; try { if (_isLocal) { File tmpFile = new File(_rootFile.getCanonicalPath() + File.separatorChar + path); if (tmpFile.isFile()) { RandomAccessFile in = new RandomAccessFile(tmpFile, "r"); in.seek((block - 1) * len); int result = -1; buffer = new byte[len]; if (in.getFilePointer() < in.length()) { result = in.read(buffer); ByteArrayOutputStream out = new ByteArrayOutputStream(result); out.write(buffer, 0, result); in.close(); return out.toByteArray(); } else { in.close(); } } } else { buffer = _remote.readFromFile(_domain, path, block, len); } } catch (Exception ex) { ex.printStackTrace(); } return buffer; }
private int readBytes(Entry entry, byte[] buffer) throws IOException { byte[] header = getHeader(entry); // entry is not compressed? if (get2ByteLittleEndian(header, 8) == 0) { zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28)); int offset = 0; int size = buffer.length; while (offset < size) { int count = zipRandomFile.read(buffer, offset, size - offset); if (count == -1) break; offset += count; } return entry.size; } int csize = entry.compressedSize; byte[] cbuf = new byte[csize]; zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28)); zipRandomFile.readFully(cbuf, 0, csize); int count = inflate(cbuf, buffer); if (count == -1) throw new ZipException("corrupted zip file"); return entry.size; }
private String readLine() throws IOException { StringBuffer sb = new StringBuffer(); char readChar; int ch; long pos = reader.getFilePointer(); long length = file.length(); if ((length < pos) || (length == pos && FileUtils.isFileNewer(file, accessTime))) { // file got rotated or truncated reader.close(); reader = new RandomAccessFile(file, "r"); position = 0; reader.seek(position); pos = 0; } accessTime = System.currentTimeMillis(); while ((ch = reader.read()) != -1) { readChar = (char) ch; if (readChar != delimiter) { sb.append(readChar); } else { return sb.toString(); } } reader.seek(pos); return null; }
public void readFileData(byte buffer[]) throws IOException { if (sourceFile != null) { RandomAccessFile sourceRandomAccessFile = new RandomAccessFile(sourceFile, "r"); sourceRandomAccessFile.read(buffer); sourceRandomAccessFile.close(); } }
public String getValueFromFile(long nextOffset, RandomAccessFile dataFile) throws IOException { int beginPtr = (int) dataFile.getFilePointer(); byte[] res = new byte[(int) (nextOffset - beginPtr)]; dataFile.read(res); String result = new String(res, StandardCharsets.UTF_8); return result; }
/** * In case an error print out the trail file context. Because of the XML reader buffering, we can * only get the block (8K). It has to be visually inspected */ protected void printErrorContext(PrintStream errOut) throws IOException { final File file = _inputStream.getCurrentFile(); final long position = _inputStream.getCurrentPosition(); File lastFile = new File(file.getParentFile(), getLastFileName()); errOut.println( "error between " + lastFile + " @ " + getLastPosition() + " and " + _inputStream.getCurrentFile() + " @ " + _inputStream.getCurrentPosition()); RandomAccessFile f = new RandomAccessFile(file, "r"); try { long startPos = lastFile.equals(file) ? getLastPosition() : 0; long endPos = position + ERROR_CONTEXT_LEN; int contextSize = (int) (endPos - startPos); byte[] context = new byte[contextSize]; f.seek(startPos); if (f.read(context, 0, contextSize) > 0) { errOut.println("context: " + new String(context, "ISO-8859-1")); } else { errOut.println("unable to read XML error context"); } } finally { f.close(); } }
public static String readString(RandomAccessFile f, long l) throws IOException { f.seek(l - 1); int length = (int) f.readUnsignedByte(); byte[] strArr = new byte[length]; f.read(strArr); return new String(strArr); }
public ByteBuffer readBacking() throws IOException { if (!_open) { return null; } ByteBuffer dst = ByteBuffer.allocate((int) _backing.length()); int length; // 4K buffer. byte[] buf = new byte[4 * (2 ^ 10)]; _backing.seek(0); // Read up to 4K blocks from the backing file while ((length = _backing.read(buf)) > 0) { try { // store the block of the correct size into the ByteBuffer. dst.put(buf, 0, length); } catch (BufferOverflowException e) { return null; } } return dst; }