Java Code Examples for java.io.RandomAccessFile#readByte()

The following examples show how to use java.io.RandomAccessFile#readByte() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SatPayloadTable.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public static boolean newLineExists(String log) throws IOException {
	File file = new File(log );
    RandomAccessFile fileHandler = new RandomAccessFile(file, "r");
    long fileLength = fileHandler.length() - 1;
    if (fileLength < 0) {
        fileHandler.close();
        return true;
    }
    fileHandler.seek(fileLength);
    byte readByte = fileHandler.readByte();
    fileHandler.close();

    if (readByte == 0xA || readByte == 0xD) {
        return true;
    }
    return false;
}
 
Example 2
Source File: ID3v1_1.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
public boolean seek(final RandomAccessFile file) throws IOException {
    final byte[] buffer = new byte[3];
    if (file.length() < 128) {
        return false;
    }

    // Check for the empty byte before the TRACK
    file.seek(file.length() - 3);
    buffer[0] = file.readByte();
    if (buffer[0] != 0) {
        return false;
    }

    // If there's a tag, it's 128 bytes long and we'll find the tag
    file.seek(file.length() - 128);

    // read the TAG value
    file.read(buffer, 0, 3);
    final String tag = new String(buffer, 0, 3);
    return tag.equals("TAG");
}
 
Example 3
Source File: FrameBodyASPI.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
public void read(final RandomAccessFile file) throws IOException, InvalidTagException {
    final int size = readHeader(file);
    if (size == 0) {
        throw new InvalidTagException("Empty Frame");
    }
    dataStart = file.readInt();
    dataLength = file.readInt();
    indexPoints = (int) file.readShort();
    bitsPerPoint = (int) file.readByte();
    fraction = new short[indexPoints];
    for (int i = 0; i < indexPoints; i++) {
        if (bitsPerPoint == 8) {
            fraction[i] = (short) file.readByte();
        } else if (bitsPerPoint == 16) {
            fraction[i] = file.readShort();
        } else {
            throw new InvalidTagException("ASPI bits per point wasn't 8 or 16");
        }
    }
}
 
Example 4
Source File: ID3v2_2Frame.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
public void read(final RandomAccessFile file) throws IOException, InvalidTagException {
    final byte[] buffer = new byte[3];

    // lets scan for a non-zero byte;
    long filePointer;
    byte b;
    do {
        filePointer = file.getFilePointer();
        b = file.readByte();
        org.farng.mp3.id3.AbstractID3v2.incrementPaddingCounter();
    } while (b == 0);
    file.seek(filePointer);
    org.farng.mp3.id3.AbstractID3v2.decrementPaddingCounter();

    // read the 3 chracter identifier
    file.read(buffer, 0, 3);
    final String identifier = new String(buffer, 0, 3);

    // is this a valid identifier?
    if (isValidID3v2FrameIdentifier(identifier) == false) {
        file.seek(file.getFilePointer() - 2);
        throw new InvalidTagException(identifier + " is not a valid ID3v2.20 frame");
    }
    this.setBody(readBody(identifier, file));
}
 
Example 5
Source File: FileSet.java    From flume-taildirectory-source with Apache License 2.0 6 votes vote down vote up
private void seekToLastLine(RandomAccessFile rReader) throws IOException {

		long fileLength = rReader.length() - 1;
		long filePointer = fileLength;
		boolean posReached = false;
		int readByte = 0;

		while (filePointer != -1 && !posReached) {
			rReader.seek(filePointer);
			readByte = rReader.readByte();
			if (readByte == 0xA) {
				if (filePointer != fileLength) {
					posReached = true;
					rReader.seek(filePointer);
				}
			} else if (readByte == 0xD && filePointer != fileLength - 1) {
				posReached = true;
				rReader.seek(filePointer);
			}

			filePointer--;
		}
	}
 
Example 6
Source File: Chunk.java    From NBT with MIT License 6 votes vote down vote up
/**
 * Reads chunk data from a RandomAccessFile. The RandomAccessFile must already be at the correct position.
 * @param raf The RandomAccessFile to read the chunk data from.
 * @param loadFlags A logical or of {@link LoadFlags} constants indicating what data should be loaded
 * @throws IOException When something went wrong during reading.
 */
public void deserialize(RandomAccessFile raf, long loadFlags) throws IOException {
	byte compressionTypeByte = raf.readByte();
	CompressionType compressionType = CompressionType.getFromID(compressionTypeByte);
	if (compressionType == null) {
		throw new IOException("invalid compression type " + compressionTypeByte);
	}
	BufferedInputStream dis = new BufferedInputStream(compressionType.decompress(new FileInputStream(raf.getFD())));
	NamedTag tag = new NBTDeserializer(false).fromStream(dis);
	if (tag != null && tag.getTag() instanceof CompoundTag) {
		data = (CompoundTag) tag.getTag();
		initReferences(loadFlags);
	} else {
		throw new IOException("invalid data tag: " + (tag == null ? "null" : tag.getClass().getName()));
	}
}
 
Example 7
Source File: MCAFile.java    From NBT with MIT License 6 votes vote down vote up
/**
 * Reads an .mca file from a {@code RandomAccessFile} into this object.
 * This method does not perform any cleanups on the data.
 * @param raf The {@code RandomAccessFile} to read from.
 * @param loadFlags A logical or of {@link LoadFlags} constants indicating what data should be loaded
 * @throws IOException If something went wrong during deserialization.
 * */
public void deserialize(RandomAccessFile raf, long loadFlags) throws IOException {
	chunks = new Chunk[1024];
	for (int i = 0; i < 1024; i++) {
		raf.seek(i * 4);
		int offset = raf.read() << 16;
		offset |= (raf.read() & 0xFF) << 8;
		offset |= raf.read() & 0xFF;
		if (raf.readByte() == 0) {
			continue;
		}
		raf.seek(4096 + i * 4);
		int timestamp = raf.readInt();
		Chunk chunk = new Chunk(timestamp);
		raf.seek(4096 * offset + 4); //+4: skip data size
		chunk.deserialize(raf, loadFlags);
		chunks[i] = chunk;
	}
}
 
Example 8
Source File: Paged.java    From btree4j with Apache License 2.0 5 votes vote down vote up
protected void read(RandomAccessFile raf) throws IOException {
    this._fhSize = raf.readShort();
    this._pageSize = raf.readInt();
    this._totalPageCount = raf.readLong();
    this._firstFreePage = raf.readLong();
    this._lastFreePage = raf.readLong();
    this._pageHeaderSize = raf.readByte();
}
 
Example 9
Source File: IOUtil.java    From PortEx with Apache License 2.0 5 votes vote down vote up
private static int nullTerminatorIndex(long offset, RandomAccessFile raf)
		throws IOException {
	raf.seek(offset);
	int index = 0;
	byte b;
	do {
		b = raf.readByte();
		index++;
	} while (b != 0);
	return index;
}
 
Example 10
Source File: Files.java    From VideoOS-Android-SDK with GNU General Public License v3.0 5 votes vote down vote up
static void modify(File file) throws IOException {
    long size = file.length();
    if (size == 0) {
        recreateZeroSizeFile(file);
        return;
    }

    RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
    accessFile.seek(size - 1);
    byte lastByte = accessFile.readByte();
    accessFile.seek(size - 1);
    accessFile.write(lastByte);
    accessFile.close();
}
 
Example 11
Source File: Files.java    From DKVideoPlayer with Apache License 2.0 5 votes vote down vote up
static void modify(File file) throws IOException {
    long size = file.length();
    if (size == 0) {
        recreateZeroSizeFile(file);
        return;
    }

    RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
    accessFile.seek(size - 1);
    byte lastByte = accessFile.readByte();
    accessFile.seek(size - 1);
    accessFile.write(lastByte);
    accessFile.close();
}
 
Example 12
Source File: Files.java    From AndroidVideoCache with Apache License 2.0 5 votes vote down vote up
static void modify(File file) throws IOException {
    long size = file.length();
    if (size == 0) {
        recreateZeroSizeFile(file);
        return;
    }

    RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
    accessFile.seek(size - 1);
    byte lastByte = accessFile.readByte();
    accessFile.seek(size - 1);
    accessFile.write(lastByte);
    accessFile.close();
}
 
Example 13
Source File: MP3File.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns true if the first MP3 frame can be found for the MP3 file argument. It is recursive and called by
 * seekMP3Frame. This is the first byte of music data and not the ID3 Tag Frame.
 *
 * @param file       MP3 file to seek
 * @param iterations recursive counter
 *
 * @return true if the first MP3 frame can be found
 *
 * @throws IOException on any I/O error
 */
private boolean seekNextMP3Frame(final RandomAccessFile file, final int iterations) throws IOException {
    final boolean syncFound;
    final byte[] buffer;
    final byte first;
    final byte second;
    final long filePointer;
    if (iterations == 0) {
        syncFound = true;
    } else {
        try {
            readFrameHeader(file);
        } catch (TagException ex) {
            return false;
        }
        final int size = getFrameSize();
        if ((size <= 0) || (size > file.length())) {
            return false;
        }
        buffer = new byte[size - 4];
        file.read(buffer);
        filePointer = file.getFilePointer();
        first = file.readByte();
        if (first == (byte) 0xFF) {
            second = (byte) (file.readByte() & (byte) 0xE0);
            if (second == (byte) 0xE0) {
                file.seek(filePointer);

                // recursively find the next frames
                syncFound = seekNextMP3Frame(file, iterations - 1);
            } else {
                syncFound = false;
            }
        } else {
            syncFound = false;
        }
    }
    return syncFound;
}
 
Example 14
Source File: Files.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
static void modify(File file) throws IOException {
    long size = file.length();
    if (size == 0) {
        recreateZeroSizeFile(file);
        return;
    }

    RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
    accessFile.seek(size - 1);
    byte lastByte = accessFile.readByte();
    accessFile.seek(size - 1);
    accessFile.write(lastByte);
    accessFile.close();
}
 
Example 15
Source File: ID3v2_3Frame.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public void read(final RandomAccessFile file) throws IOException, InvalidTagException {
    byte b;
    long filePointer;
    final byte[] buffer = new byte[4];

    // lets scan for a non-zero byte;
    do {
        filePointer = file.getFilePointer();
        b = file.readByte();
        org.farng.mp3.id3.AbstractID3v2.incrementPaddingCounter();
    } while (b == 0);
    file.seek(filePointer);
    org.farng.mp3.id3.AbstractID3v2.decrementPaddingCounter();

    // read the four character identifier
    file.read(buffer, 0, 4);
    final String identifier = new String(buffer, 0, 4);

    // is this a valid identifier?
    if (isValidID3v2FrameIdentifier(identifier) == false) {
        file.seek(file.getFilePointer() - 3);
        throw new InvalidTagException(identifier + " is not a valid ID3v2.30 frame");
    }
    filePointer = file.getFilePointer();

    // skip the 4 byte size
    file.skipBytes(4);

    // read the flag bytes
    file.read(buffer, 0, 2);
    this.tagAlterPreservation = (buffer[0] & TagConstant.MASK_V23_TAG_ALTER_PRESERVATION) != 0;
    this.fileAlterPreservation = (buffer[0] & TagConstant.MASK_V23_FILE_ALTER_PRESERVATION) != 0;
    this.readOnly = (buffer[0] & TagConstant.MASK_V23_READ_ONLY) != 0;
    this.compression = (buffer[1] & TagConstant.MASK_V23_COMPRESSION) != 0;
    this.encryption = (buffer[1] & TagConstant.MASK_V23_ENCRYPTION) != 0;
    this.groupingIdentity = (buffer[1] & TagConstant.MASK_V23_GROUPING_IDENTITY) != 0;
    file.seek(filePointer);
    this.setBody(readBody(identifier, file));
}
 
Example 16
Source File: Files.java    From AndriodVideoCache with Apache License 2.0 5 votes vote down vote up
static void modify(File file) throws IOException {
    long size = file.length();
    if (size == 0) {
        recreateZeroSizeFile(file);
        return;
    }

    RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
    accessFile.seek(size - 1);
    byte lastByte = accessFile.readByte();
    accessFile.seek(size - 1);
    accessFile.write(lastByte);
    accessFile.close();
}
 
Example 17
Source File: RegionLoader.java    From Nukkit with GNU General Public License v3.0 4 votes vote down vote up
public Chunk readChunk(int x, int z) throws IOException {
    int index = getChunkOffset(x, z);
    if (index < 0 || index >= 4096) {
        return null;
    }

    this.lastUsed = System.currentTimeMillis();

    if (!this.isChunkGenerated(index)) {
        return null;
    }

    Integer[] table = this.locationTable.get(index);
    RandomAccessFile raf = this.getRandomAccessFile();
    raf.seek(table[0] << 12);
    int length = raf.readInt();
    if (length <= 0 || length >= MAX_SECTOR_LENGTH) {
        if (length >= MAX_SECTOR_LENGTH) {
            table[0] = ++this.lastSector;
            table[1] = 1;
            this.locationTable.put(index, table);
            MainLogger.getLogger().error("Corrupted chunk header detected");
        }
        return null;
    }

    byte compression = raf.readByte();
    if (length > (table[1] << 12)) {
        MainLogger.getLogger().error("Corrupted bigger chunk detected");
        table[1] = length >> 12;
        this.locationTable.put(index, table);
        this.writeLocationIndex(index);
    } else if (compression != COMPRESSION_ZLIB && compression != COMPRESSION_GZIP) {
        MainLogger.getLogger().error("Invalid compression type");
        return null;
    }

    byte[] data = new byte[length - 1];
    raf.readFully(data);
    Chunk chunk = this.unserializeChunk(data);
    if (chunk != null) {
        return chunk;
    } else {
        MainLogger.getLogger().error("Corrupted chunk detected");
        return null;
    }
}
 
Example 18
Source File: RegionLoader.java    From Nukkit with GNU General Public License v3.0 4 votes vote down vote up
public Chunk readChunk(int x, int z) throws IOException {
    int index = getChunkOffset(x, z);
    if (index < 0 || index >= 4096) {
        return null;
    }

    this.lastUsed = System.currentTimeMillis();

    if (!this.isChunkGenerated(index)) {
        return null;
    }

    Integer[] table = this.locationTable.get(index);
    RandomAccessFile raf = this.getRandomAccessFile();
    raf.seek(table[0] << 12);
    int length = raf.readInt();
    if (length <= 0 || length >= MAX_SECTOR_LENGTH) {
        if (length >= MAX_SECTOR_LENGTH) {
            table[0] = ++this.lastSector;
            table[1] = 1;
            this.locationTable.put(index, table);
            MainLogger.getLogger().error("Corrupted chunk header detected");
        }
        return null;
    }

    byte compression = raf.readByte();
    if (length > (table[1] << 12)) {
        MainLogger.getLogger().error("Corrupted bigger chunk detected");
        table[1] = length >> 12;
        this.locationTable.put(index, table);
        this.writeLocationIndex(index);
    } else if (compression != COMPRESSION_ZLIB && compression != COMPRESSION_GZIP) {
        MainLogger.getLogger().error("Invalid compression type");
        return null;
    }

    byte[] data = new byte[length - 1];
    raf.readFully(data);
    Chunk chunk = this.unserializeChunk(data);
    if (chunk != null) {
        return chunk;
    } else {
        MainLogger.getLogger().error("Corrupted chunk detected");
        return null;
    }
}
 
Example 19
Source File: AACStream.java    From libstreaming with Apache License 2.0 4 votes vote down vote up
/** 
 * Records a short sample of AAC ADTS from the microphone to find out what the sampling rate really is
 * On some phone indeed, no error will be reported if the sampling rate used differs from the 
 * one selected with setAudioSamplingRate 
 * @throws IOException 
 * @throws IllegalStateException
 */
@SuppressLint("InlinedApi")
private void testADTS() throws IllegalStateException, IOException {
	
	setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
	try {
		Field name = MediaRecorder.OutputFormat.class.getField("AAC_ADTS");
		setOutputFormat(name.getInt(null));
	}
	catch (Exception ignore) {
		setOutputFormat(6);
	}

	String key = PREF_PREFIX+"aac-"+mQuality.samplingRate;

	if (mSettings!=null && mSettings.contains(key)) {
		String[] s = mSettings.getString(key, "").split(",");
		mQuality.samplingRate = Integer.valueOf(s[0]);
		mConfig = Integer.valueOf(s[1]);
		mChannel = Integer.valueOf(s[2]);
		return;
	}

	final String TESTFILE = Environment.getExternalStorageDirectory().getPath()+"/spydroid-test.adts";

	if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
		throw new IllegalStateException("No external storage or external storage not ready !");
	}

	// The structure of an ADTS packet is described here: http://wiki.multimedia.cx/index.php?title=ADTS

	// ADTS header is 7 or 9 bytes long
	byte[] buffer = new byte[9];

	mMediaRecorder = new MediaRecorder();
	mMediaRecorder.setAudioSource(mAudioSource);
	mMediaRecorder.setOutputFormat(mOutputFormat);
	mMediaRecorder.setAudioEncoder(mAudioEncoder);
	mMediaRecorder.setAudioChannels(1);
	mMediaRecorder.setAudioSamplingRate(mQuality.samplingRate);
	mMediaRecorder.setAudioEncodingBitRate(mQuality.bitRate);
	mMediaRecorder.setOutputFile(TESTFILE);
	mMediaRecorder.setMaxDuration(1000);
	mMediaRecorder.prepare();
	mMediaRecorder.start();

	// We record for 1 sec
	// TODO: use the MediaRecorder.OnInfoListener
	try {
		Thread.sleep(2000);
	} catch (InterruptedException e) {}

	mMediaRecorder.stop();
	mMediaRecorder.release();
	mMediaRecorder = null;

	File file = new File(TESTFILE);
	RandomAccessFile raf = new RandomAccessFile(file, "r");

	// ADTS packets start with a sync word: 12bits set to 1
	while (true) {
		if ( (raf.readByte()&0xFF) == 0xFF ) {
			buffer[0] = raf.readByte();
			if ( (buffer[0]&0xF0) == 0xF0) break;
		}
	}

	raf.read(buffer,1,5);

	mSamplingRateIndex = (buffer[1]&0x3C)>>2 ;
	mProfile = ( (buffer[1]&0xC0) >> 6 ) + 1 ;
	mChannel = (buffer[1]&0x01) << 2 | (buffer[2]&0xC0) >> 6 ;
	mQuality.samplingRate = AUDIO_SAMPLING_RATES[mSamplingRateIndex];

	// 5 bits for the object type / 4 bits for the sampling rate / 4 bits for the channel / padding
	mConfig = (mProfile & 0x1F) << 11 | (mSamplingRateIndex & 0x0F) << 7 | (mChannel & 0x0F) << 3;

	Log.i(TAG,"MPEG VERSION: " + ( (buffer[0]&0x08) >> 3 ) );
	Log.i(TAG,"PROTECTION: " + (buffer[0]&0x01) );
	Log.i(TAG,"PROFILE: " + AUDIO_OBJECT_TYPES[ mProfile ] );
	Log.i(TAG,"SAMPLING FREQUENCY: " + mQuality.samplingRate );
	Log.i(TAG,"CHANNEL: " + mChannel );

	raf.close();

	if (mSettings!=null) {
		Editor editor = mSettings.edit();
		editor.putString(key, mQuality.samplingRate+","+mConfig+","+mChannel);
		editor.commit();
	}

	if (!file.delete()) Log.e(TAG,"Temp file could not be erased");

}
 
Example 20
Source File: ID3v2_4Frame.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public void read(final RandomAccessFile file) throws IOException, InvalidTagException {
    long filePointer;
    final byte[] buffer = new byte[4];
    byte b;

    // lets scan for a non-zero byte;
    do {
        filePointer = file.getFilePointer();
        b = file.readByte();
        org.farng.mp3.id3.AbstractID3v2.incrementPaddingCounter();
    } while (b == 0);
    file.seek(filePointer);
    org.farng.mp3.id3.AbstractID3v2.decrementPaddingCounter();

    // read the four character identifier
    file.read(buffer, 0, 4);
    final String identifier = new String(buffer, 0, 4);

    // is this a valid identifier?
    if (isValidID3v2FrameIdentifier(identifier) == false) {
        file.seek(file.getFilePointer() - 3);
        throw new InvalidTagException(identifier + " is not a valid ID3v2.40 frame");
    }
    filePointer = file.getFilePointer();

    // skip the 4 byte size
    file.skipBytes(4);

    // read the flag bytes
    file.read(buffer, 0, 2);
    this.tagAlterPreservation = (buffer[0] & TagConstant.MASK_V24_TAG_ALTER_PRESERVATION) != 0;
    this.fileAlterPreservation = (buffer[0] & TagConstant.MASK_V24_FILE_ALTER_PRESERVATION) != 0;
    this.readOnly = (buffer[0] & TagConstant.MASK_V24_READ_ONLY) != 0;
    this.groupingIdentity = (buffer[1] & TagConstant.MASK_V24_GROUPING_IDENTITY) != 0;
    this.compression = (buffer[1] & TagConstant.MASK_V24_COMPRESSION) != 0;
    this.encryption = (buffer[1] & TagConstant.MASK_V24_ENCRYPTION) != 0;
    this.unsynchronization = (buffer[1] & TagConstant.MASK_V24_FRAME_UNSYNCHRONIZATION) != 0;
    this.dataLengthIndicator = (buffer[1] & TagConstant.MASK_V24_DATA_LENGTH_INDICATOR) != 0;
    file.seek(filePointer);
    this.setBody(readBody(identifier, file));
}