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

The following examples show how to use java.io.RandomAccessFile#writeByte() . 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: PythonSender.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
public void open(File outputFile) throws IOException {
	outputFile.mkdirs();

	if (outputFile.exists()) {
		outputFile.delete();
	}
	outputFile.createNewFile();
	outputRAF = new RandomAccessFile(outputFile, "rw");

	outputRAF.setLength(mappedFileSizeBytes);
	outputRAF.seek(mappedFileSizeBytes - 1);
	outputRAF.writeByte(0);
	outputRAF.seek(0);
	outputChannel = outputRAF.getChannel();
	fileBuffer = outputChannel.map(FileChannel.MapMode.READ_WRITE, 0, mappedFileSizeBytes);
}
 
Example 2
Source File: UpgradeUtilities.java    From hadoop-gpu with Apache License 2.0 6 votes vote down vote up
/**
 * Corrupt the specified file.  Some random bytes within the file
 * will be changed to some random values.
 *
 * @throws IllegalArgumentException if the given file is not a file
 * @throws IOException if an IOException occurs while reading or writing the file
 */
public static void corruptFile(File file) throws IOException {
  if (!file.isFile()) {
    throw new IllegalArgumentException(
                                       "Given argument is not a file:" + file);
  }
  RandomAccessFile raf = new RandomAccessFile(file,"rws");
  Random random = new Random();
  for (long i = 0; i < raf.length(); i++) {
    raf.seek(i);
    if (random.nextBoolean()) {
      raf.writeByte(random.nextInt());
    }
  }
  raf.close();
}
 
Example 3
Source File: UpgradeUtilities.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Corrupt the specified file.  Some random bytes within the file
 * will be changed to some random values.
 *
 * @throws IllegalArgumentException if the given file is not a file
 * @throws IOException if an IOException occurs while reading or writing the file
 */
public static void corruptFile(File file) throws IOException {
  if (!file.isFile()) {
    throw new IllegalArgumentException(
                                       "Given argument is not a file:" + file);
  }
  RandomAccessFile raf = new RandomAccessFile(file,"rws");
  Random random = new Random();
  for (long i = 0; i < raf.length(); i++) {
    raf.seek(i);
    if (random.nextBoolean()) {
      raf.writeByte(random.nextInt());
    }
  }
  raf.close();
}
 
Example 4
Source File: PythonReceiver.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void open(File inputFile) throws IOException {
	deserializer = (Deserializer<OUT>) (readAsByteArray ? new ByteArrayDeserializer() : new TupleDeserializer());

	inputFile.getParentFile().mkdirs();

	if (inputFile.exists()) {
		inputFile.delete();
	}
	inputFile.createNewFile();
	inputRAF = new RandomAccessFile(inputFile, "rw");
	inputRAF.setLength(mappedFileSizeBytes);
	inputRAF.seek(mappedFileSizeBytes - 1);
	inputRAF.writeByte(0);
	inputRAF.seek(0);
	inputChannel = inputRAF.getChannel();
	fileBuffer = inputChannel.map(FileChannel.MapMode.READ_WRITE, 0, mappedFileSizeBytes);
}
 
Example 5
Source File: TestFSEditLogLoader.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Corrupt the byte at the given offset in the given file,
 * by subtracting 1 from it.
 */
private void corruptByteInFile(File file, long offset)
    throws IOException {
  RandomAccessFile raf = new RandomAccessFile(file, "rw");
  try {
    raf.seek(offset);
    int origByte = raf.read();
    raf.seek(offset);
    raf.writeByte(origByte - 1);
  } finally {
    IOUtils.closeStream(raf);
  }
}
 
Example 6
Source File: Paged.java    From btree4j with Apache License 2.0 5 votes vote down vote up
protected void write(RandomAccessFile raf) throws IOException {
    raf.writeShort(_fhSize);
    raf.writeInt(_pageSize);
    raf.writeLong(_totalPageCount);
    raf.writeLong(_firstFreePage);
    raf.writeLong(_lastFreePage);
    raf.writeByte(_pageHeaderSize);
}
 
Example 7
Source File: Chunk.java    From NBT with MIT License 5 votes vote down vote up
/**
 * Serializes this chunk to a <code>RandomAccessFile</code>.
 * @param raf The RandomAccessFile to be written to.
 * @param xPos The x-coordinate of the chunk.
 * @param zPos The z-coodrinate of the chunk.
 * @return The amount of bytes written to the RandomAccessFile.
 * @throws UnsupportedOperationException When something went wrong during writing.
 * @throws IOException When something went wrong during writing.
 */
public int serialize(RandomAccessFile raf, int xPos, int zPos) throws IOException {
	if (partial) {
		throw new UnsupportedOperationException("Partially loaded chunks cannot be serialized");
	}
	ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
	try (BufferedOutputStream nbtOut = new BufferedOutputStream(CompressionType.ZLIB.compress(baos))) {
		new NBTSerializer(false).toStream(new NamedTag(null, updateHandle(xPos, zPos)), nbtOut);
	}
	byte[] rawData = baos.toByteArray();
	raf.writeInt(rawData.length + 1); // including the byte to store the compression type
	raf.writeByte(CompressionType.ZLIB.getID());
	raf.write(rawData);
	return rawData.length + 5;
}
 
Example 8
Source File: TestFSEditLogLoader.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Corrupt the byte at the given offset in the given file,
 * by subtracting 1 from it.
 */
private void corruptByteInFile(File file, long offset)
    throws IOException {
  RandomAccessFile raf = new RandomAccessFile(file, "rw");
  try {
    raf.seek(offset);
    int origByte = raf.read();
    raf.seek(offset);
    raf.writeByte(origByte - 1);
  } finally {
    IOUtils.closeStream(raf);
  }
}
 
Example 9
Source File: FrameBodyASPI.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public void write(final RandomAccessFile file) throws IOException {
    writeHeader(file, getSize());
    file.writeInt(dataStart);
    file.writeInt(dataLength);
    file.writeShort(indexPoints);
    file.writeByte(16);
    for (int i = 0; i < indexPoints; i++) {
        file.writeShort((int) fraction[i]);
    }
}
 
Example 10
Source File: RandomAccessFileTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.io.RandomAccessFile#readByte()
 */
public void test_readByte() throws IOException {
    // Test for method byte java.io.RandomAccessFile.readByte()
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
    raf.writeByte(127);
    raf.seek(0);
    assertEquals("Incorrect bytes read/written", 127, raf.readByte());
    raf.close();
}
 
Example 11
Source File: RandomAccessFileTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.io.RandomAccessFile#readUnsignedByte()
 */
public void test_readUnsignedByte() throws IOException {
    // Test for method int java.io.RandomAccessFile.readUnsignedByte()
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
    raf.writeByte(-1);
    raf.seek(0);
    assertEquals("Incorrect byte read/written", 255, raf.readUnsignedByte());
    raf.close();
}
 
Example 12
Source File: RandomAccessFileTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.io.RandomAccessFile#writeByte(int)
 */
public void test_writeByteI() throws IOException {
    // Test for method void java.io.RandomAccessFile.writeByte(int)
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
    raf.writeByte(127);
    raf.seek(0);
    assertEquals("Incorrect byte read/written", 127, raf.readByte());
    raf.close();
}
 
Example 13
Source File: TestFileChannel.java    From mt-flume with Apache License 2.0 5 votes vote down vote up
@Test (expected = IllegalStateException.class)
public void testChannelDiesOnCorruptEvent() throws Exception {
  final FileChannel channel = createFileChannel();
  channel.start();
  putEvents(channel,"test-corrupt-event",100,100);
  for(File dataDir : dataDirs) {
    File[] files = dataDir.listFiles(new FilenameFilter() {
      @Override
      public boolean accept(File dir, String name) {
        if(!name.endsWith("meta") && !name.contains("lock")){
          return true;
        }
        return false;
      }
    });
    if (files != null && files.length > 0) {
      for (int j = 0; j < files.length; j++) {
        RandomAccessFile fileToCorrupt = new RandomAccessFile(files[0], "rw");
        fileToCorrupt.seek(50);
        fileToCorrupt.writeByte(234);
        fileToCorrupt.close();
      }
    }
  }
  try {
    consumeChannel(channel, true);
  } catch (IllegalStateException ex) {
    // The rollback call in takeEvents() in TestUtils will cause an
    // IllegalArgumentException - and this should be tested to verify the
    // channel is completely stopped.
    Assert.assertTrue(ex.getMessage().contains("Log is closed"));
    throw ex;
  }
  Assert.fail();


}
 
Example 14
Source File: ElfHeader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @see ghidra.app.util.bin.format.Writeable#write(java.io.RandomAccessFile, ghidra.util.DataConverter)
 */
@Override
public void write(RandomAccessFile raf, DataConverter dc) throws IOException {
	raf.seek(0);
	raf.writeByte(e_ident_magic_num);
	raf.write(e_ident_magic_str.getBytes());
	raf.writeByte(e_ident_class);
	raf.writeByte(e_ident_data);
	raf.writeByte(e_ident_version);
	raf.writeByte(e_ident_osabi);
	raf.writeByte(e_ident_abiversion);
	raf.write(e_ident_pad);
	raf.write(dc.getBytes(e_type));
	raf.write(dc.getBytes(e_machine));
	raf.write(dc.getBytes(e_version));

	if (is32Bit()) {
		raf.write(dc.getBytes((int) e_entry));
		raf.write(dc.getBytes((int) e_phoff));
		raf.write(dc.getBytes((int) e_shoff));
	}
	else if (is64Bit()) {
		raf.write(dc.getBytes(e_entry));
		raf.write(dc.getBytes(e_phoff));
		raf.write(dc.getBytes(e_shoff));
	}

	raf.write(dc.getBytes(e_flags));
	raf.write(dc.getBytes(e_ehsize));
	raf.write(dc.getBytes(e_phentsize));
	raf.write(dc.getBytes(e_phnum));
	raf.write(dc.getBytes(e_shentsize));
	raf.write(dc.getBytes(e_shnum));
	raf.write(dc.getBytes(e_shstrndx));
}
 
Example 15
Source File: CacheFileContent.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
/**
 * Write the current cache file content to the given random access file.
 */
void write(@NonNullable RandomAccessFile raf) throws IOException {
    // File content type.
    raf.writeByte(this.contentType);
    // Byte array length.
    raf.writeInt(this.contentLength);
    // Byte array hashcode.
    raf.writeInt(this.contentHashCode);
    // Byte array.
    raf.write(this.content);
}
 
Example 16
Source File: MCAFile.java    From NBT with MIT License 4 votes vote down vote up
/**
 * Serializes this object to an .mca file.
 * This method does not perform any cleanups on the data.
 * @param raf The {@code RandomAccessFile} to write to.
 * @param changeLastUpdate Whether it should update all timestamps that show
 *                         when this file was last updated.
 * @return The amount of chunks written to the file.
 * @throws IOException If something went wrong during serialization.
 * */
public int serialize(RandomAccessFile raf, boolean changeLastUpdate) throws IOException {
	int globalOffset = 2;
	int lastWritten = 0;
	int timestamp = (int) (System.currentTimeMillis() / 1000L);
	int chunksWritten = 0;
	int chunkXOffset = MCAUtil.regionToChunk(regionX);
	int chunkZOffset = MCAUtil.regionToChunk(regionZ);

	if (chunks == null) {
		return 0;
	}

	for (int cx = 0; cx < 32; cx++) {
		for (int cz = 0; cz < 32; cz++) {
			int index = getChunkIndex(cx, cz);
			Chunk chunk = chunks[index];
			if (chunk == null) {
				continue;
			}
			raf.seek(4096 * globalOffset);
			lastWritten = chunk.serialize(raf, chunkXOffset + cx, chunkZOffset + cz);

			if (lastWritten == 0) {
				continue;
			}

			chunksWritten++;

			int sectors = (lastWritten >> 12) + (lastWritten % 4096 == 0 ? 0 : 1);

			raf.seek(index * 4);
			raf.writeByte(globalOffset >>> 16);
			raf.writeByte(globalOffset >> 8 & 0xFF);
			raf.writeByte(globalOffset & 0xFF);
			raf.writeByte(sectors);

			// write timestamp
			raf.seek(index * 4 + 4096);
			raf.writeInt(changeLastUpdate ? timestamp : chunk.getLastMCAUpdate());

			globalOffset += sectors;
		}
	}

	// padding
	if (lastWritten % 4096 != 0) {
		raf.seek(globalOffset * 4096 - 1);
		raf.write(0);
	}
	return chunksWritten;
}
 
Example 17
Source File: ID3v2_4.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public void write(final RandomAccessFile file) throws IOException {
    int size;
    final String str;
    final Iterator iterator;
    ID3v2_4Frame frame;
    final byte[] buffer = new byte[6];
    final MP3File mp3 = new MP3File();
    mp3.seekMP3Frame(file);
    final long mp3start = file.getFilePointer();
    file.seek(0);
    str = "ID3";
    for (int i = 0; i < str.length(); i++) {
        buffer[i] = (byte) str.charAt(i);
    }
    buffer[3] = 4;
    buffer[4] = 0;
    if (this.unsynchronization) {
        buffer[5] |= TagConstant.MASK_V24_UNSYNCHRONIZATION;
    }
    if (this.extended) {
        buffer[5] |= TagConstant.MASK_V24_EXTENDED_HEADER;
    }
    if (this.experimental) {
        buffer[5] |= TagConstant.MASK_V24_EXPERIMENTAL;
    }
    if (this.footer) {
        buffer[5] |= TagConstant.MASK_V24_FOOTER_PRESENT;
    }
    file.write(buffer);

    // write size
    file.write(sizeToByteArray((int) mp3start - 10));
    if (this.extended) {
        size = 6;
        if (this.updateTag) {
            size++;
        }
        if (this.crcDataFlag) {
            size += 5;
        }
        if (this.tagRestriction) {
            size += 2;
        }
        file.writeInt(size);
        file.writeByte(1); // always 1 byte of flags in this tag
        buffer[0] = 0;
        if (this.updateTag) {
            buffer[0] |= TagConstant.MASK_V24_TAG_UPDATE;
        }
        if (this.crcDataFlag) {
            buffer[0] |= TagConstant.MASK_V24_CRC_DATA_PRESENT;
        }
        if (this.tagRestriction) {
            buffer[0] |= TagConstant.MASK_V24_TAG_RESTRICTIONS;
        }
        file.writeByte(buffer[0]);
        if (this.updateTag) {
            file.writeByte(0);
        }

        // this can be variable length, but this is easier
        if (this.crcDataFlag) {
            file.writeByte(4);
            file.writeInt(this.crcData);
        }
        if (this.tagRestriction) {
            // todo we need to finish this
            file.writeByte(1);
            buffer[0] = (byte) 0;
            if (this.tagRestriction) {
                buffer[0] |= TagConstant.MASK_V24_TAG_SIZE_RESTRICTIONS;
            }
            file.writeByte(this.tagSizeRestriction);
            file.writeByte(this.textEncodingRestriction);
            file.writeByte(this.textFieldSizeRestriction);
            file.writeByte(this.imageEncodingRestriction);
            file.writeByte(this.imageSizeRestriction);
            file.writeByte(buffer[0]);
        }
    }

    // write all frames
    iterator = this.getFrameIterator();
    while (iterator.hasNext()) {
        frame = (ID3v2_4Frame) iterator.next();
        frame.write(file);
    }
}