本文整理汇总了Java中java.nio.ByteBuffer类的典型用法代码示例。如果您正苦于以下问题:Java ByteBuffer类的具体用法?Java ByteBuffer怎么用?Java ByteBuffer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ByteBuffer类属于java.nio包,在下文中一共展示了ByteBuffer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getDiskStoreIdFromInitFile
import java.nio.ByteBuffer; //导入依赖的package包/类
private String getDiskStoreIdFromInitFile(File dir, String fileName)
throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream(new File(dir, fileName));
try {
byte[] bytes = new byte[1 + 8 + 8];
fis.read(bytes);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
// Skip the record type.
buffer.get();
long least = buffer.getLong();
long most = buffer.getLong();
UUID id = new UUID(most, least);
return id.toString();
} finally {
fis.close();
}
}
示例2: main
import java.nio.ByteBuffer; //导入依赖的package包/类
public static void main(String[] args) {
Path file = Paths.get(System.getProperty("user.home") + "/test/myfile.txt");
try (SeekableByteChannel sbc = Files.newByteChannel(file)) { // |\longremark{newByteChannel默认返回只读的Channel}|
ByteBuffer buf = ByteBuffer.allocate(10); // |\longremark{allocate创建一个指定字节的ByteBuffer,本例中,sbc这个Channel每次读取10个字节}|
String encoding = System.getProperty("file.encoding"); // |\longremark{获得当前系统文件编码方式,以便读取文件字节后解码}|
while (sbc.read(buf) > 0) { // |\longremark{从通道读数据到缓冲区}|
buf.flip(); // |\longremark{切换缓冲区为读模式}|
System.out.print(Charset.forName(encoding).decode(buf));
buf.clear(); // |\longremark{清空缓冲区,准备写入下一轮数据}|
}
} catch (IOException x) {
System.out.println("caught exception: " + x);
}
}
示例3: parseCharArray
import java.nio.ByteBuffer; //导入依赖的package包/类
private static Object parseCharArray(int length,
ByteBuffer buf, ConstantPool constPool) {
char[] result = new char[length];
boolean typeMismatch = false;
byte tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'C') {
int index = buf.getShort() & 0xFFFF;
result[i] = (char) constPool.getIntAt(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
示例4: init
import java.nio.ByteBuffer; //导入依赖的package包/类
@Override
protected void init(ByteBuffer buffer) {
super.init(buffer);
for (Chunk chunk : getChunks().values()) {
if (chunk instanceof TypeChunk) {
TypeChunk typeChunk = (TypeChunk) chunk;
types.put(typeChunk.getId(), typeChunk);
} else if (chunk instanceof TypeSpecChunk) {
TypeSpecChunk typeSpecChunk = (TypeSpecChunk) chunk;
typeSpecs.put(typeSpecChunk.getId(), typeSpecChunk);
} else if (chunk instanceof StringPoolChunk) {
continue;
} else if (chunk instanceof LibraryChunk) {
LibraryChunk libraryChunk = (LibraryChunk) chunk;
libraries.add(libraryChunk);
} else {
throw new IllegalStateException(String.format("PackageChunk contains an unexpected chunk: %s", chunk.getClass()));
}
}
}
示例5: dequeueOutputBuffer
import java.nio.ByteBuffer; //导入依赖的package包/类
/**
* Save the encoded (output) buffer into the complete encoded recording.
* TODO: copy directly (without the intermediate byte array)
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void dequeueOutputBuffer(MediaCodec codec, ByteBuffer[] outputBuffers, int index, MediaCodec.BufferInfo info) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
ByteBuffer buffer = outputBuffers[index];
Log.i("size/remaining: " + info.size + "/" + buffer.remaining());
if (info.size <= buffer.remaining()) {
final byte[] bufferCopied = new byte[info.size];
buffer.get(bufferCopied); // TODO: catch BufferUnderflow
// TODO: do we need to clear?
// on N5: always size == remaining(), clearing is not needed
// on SGS2: remaining decreases until it becomes less than size, which results in BufferUnderflow
// (but SGS2 records only zeros anyway)
//buffer.clear();
codec.releaseOutputBuffer(index, false);
addEncoded(bufferCopied);
if (Log.DEBUG) {
AudioUtils.showSomeBytes("out", bufferCopied);
}
} else {
Log.e("size > remaining");
codec.releaseOutputBuffer(index, false);
}
}
}
开发者ID:vaibhavs4424,项目名称:AI-Powered-Intelligent-Banking-Platform,代码行数:29,代码来源:EncodedAudioRecorder.java
示例6: run
import java.nio.ByteBuffer; //导入依赖的package包/类
@Override
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(Options.getInstance().bufferSize);
while (running) {
try {
selector.select();
Set selectedKeys = selector.selectedKeys();
for (Object selectedKey : selectedKeys) {
SelectionKey key = (SelectionKey) selectedKey;
SocketChannel channel = (SocketChannel) key.channel();
channel.read(buffer);
//TODO
}
} catch (IOException e) {
Lg.e(Error.READER, e);
}
}
}
示例7: writeImageDescriptor
import java.nio.ByteBuffer; //导入依赖的package包/类
public static void writeImageDescriptor(ByteBuffer out, int imageLeft, int imageTop,
int imageWidth, int imageHeight, boolean hasLct, int numColors) {
verifyRemaining(out, IMAGE_DESCRIPTOR_LENGTH);
verifyShortValues(imageLeft, imageTop, imageWidth, imageHeight);
final byte packed;
if (hasLct) {
int size = log2(numColors) - 1;
packed = (byte) (0x80 | size);
} else {
packed = 0x00;
}
// Image separator
out.put((byte) 0x2C);
out.putShort((short) imageLeft).putShort((short) imageTop).putShort((short) imageWidth)
.putShort((short) imageHeight).put(packed);
}
示例8: compare
import java.nio.ByteBuffer; //导入依赖的package包/类
public int compare(ByteBuffer buffer1, byte[] buffer2, int offset2, int length2) {
Object obj1;
long offset1;
if (buffer1.hasArray()) {
obj1 = buffer1.array();
offset1 = BYTE_ARRAY_BASE_OFFSET + buffer1.arrayOffset();
} else {
obj1 = null;
offset1 = THE_UNSAFE.getLong(buffer1, DIRECT_BUFFER_ADDRESS_OFFSET);
}
int length1;
{
int position = buffer1.position();
int limit = buffer1.limit();
length1 = limit - position;
offset1 += position;
}
return compareTo(obj1, offset1, length1, buffer2, BYTE_ARRAY_BASE_OFFSET + offset2, length2);
}
示例9: calculateChecksumOverPage
import java.nio.ByteBuffer; //导入依赖的package包/类
/**
* Calculate checkSum over the Page
*
* @param page
*/
private void calculateChecksumOverPage(ByteBuffer page)
{
//CRC should be zero before calculating it
page.putInt(OggPageHeader.FIELD_PAGE_CHECKSUM_POS, 0);
//Compute CRC over the page //TODO shouldnt really use array();
byte[] crc = OggCRCFactory.computeCRC(page.array());
for (int i = 0; i < crc.length; i++)
{
page.put(OggPageHeader.FIELD_PAGE_CHECKSUM_POS + i, crc[i]);
}
//Rewind to start of Page
page.rewind();
}
示例10: testGetParameterSet
import java.nio.ByteBuffer; //导入依赖的package包/类
/**
* testGetParameterSet
*/
public void testGetParameterSet() throws Exception {
StoredProcedureInvocation invocation = new StoredProcedureInvocation(CLIENT_HANDLE,
TARGET_PROCEDURE,
PARAMS);
byte[] invocation_bytes = FastSerializer.serialize(invocation);
assertNotNull(invocation_bytes);
ByteBuffer buffer = ByteBuffer.wrap(invocation_bytes);
ByteBuffer paramsBuffer = StoredProcedureInvocation.getParameterSet(buffer);
assertNotNull(paramsBuffer);
ParameterSet cloneParams = new ParameterSet();
FastDeserializer fds = new FastDeserializer(paramsBuffer);
cloneParams.readExternal(fds);
assertEquals(PARAMS.length, cloneParams.size());
for (int i = 0; i < PARAMS.length; i++) {
assertEquals(PARAMS[i], cloneParams.toArray()[i]);
}
}
示例11: buildSlice
import java.nio.ByteBuffer; //导入依赖的package包/类
/** Returns a sliced view from a set of already-existing buffers:
* the last buffer's limit() will be correct, but
* you must deal with offset separately (the first buffer will not be adjusted) */
private ByteBuffer[] buildSlice(ByteBuffer[] buffers, long offset, long length) {
final long sliceEnd = offset + length;
final int startIndex = (int) (offset >>> chunkSizePower);
final int endIndex = (int) (sliceEnd >>> chunkSizePower);
// we always allocate one more slice, the last one may be a 0 byte one
final ByteBuffer slices[] = new ByteBuffer[endIndex - startIndex + 1];
for (int i = 0; i < slices.length; i++) {
slices[i] = buffers[startIndex + i].duplicate();
}
// set the last buffer's limit for the sliced view.
slices[slices.length - 1].limit((int) (sliceEnd & chunkSizeMask));
return slices;
}
示例12: transform
import java.nio.ByteBuffer; //导入依赖的package包/类
@Override
public ResourcePool transform(ResourcePool in, ResourcePoolBuilder out) {
in.transformAndCopy((resource) -> {
ResourcePoolEntry res = resource;
if (resource.type().equals(ResourcePoolEntry.Type.CLASS_OR_RESOURCE)
&& predicate.test(resource.path())) {
byte[] compressed;
compressed = compress(resource.contentBytes());
res = ResourcePoolManager.newCompressedResource(resource,
ByteBuffer.wrap(compressed), getName(), null,
((ResourcePoolImpl)in).getStringTable(), in.byteOrder());
}
return res;
}, out);
return out.build();
}
示例13: testArrayBackedBufferSlice
import java.nio.ByteBuffer; //导入依赖的package包/类
@Test
public void testArrayBackedBufferSlice() throws IOException {
byte[] compressed = compressedBytes();
int sliceOffset = 12;
ByteBuffer buffer = ByteBuffer.allocate(compressed.length + sliceOffset + 123);
buffer.position(sliceOffset);
buffer.put(compressed).flip();
buffer.position(sliceOffset);
ByteBuffer slice = buffer.slice();
testDecompression(slice);
int offset = 42;
buffer = ByteBuffer.allocate(compressed.length + sliceOffset + offset);
buffer.position(sliceOffset + offset);
buffer.put(compressed).flip();
buffer.position(sliceOffset);
slice = buffer.slice();
slice.position(offset);
testDecompression(slice);
}
示例14: writeFlvMetaData
import java.nio.ByteBuffer; //导入依赖的package包/类
/**
* 生成flv medadata 数据
* @param width 视频宽度
* @param height 视频高度
* @param fps 视频帧率
* @param audioRate 音频采样率
* @param audioSize 音频大小
* @param isStereo 音频是否为立体声
* @return byte数组
*/
public static byte[] writeFlvMetaData(int width, int height, int fps, int audioRate, int audioSize, boolean isStereo) {
AmfString metaDataHeader = new AmfString("onMetaData", false);
AmfMap amfMap = new AmfMap();
amfMap.setProperty("width", width);
amfMap.setProperty("height", height);
amfMap.setProperty("framerate", fps);
amfMap.setProperty("videocodecid", FlvVideoCodecID.AVC);
amfMap.setProperty("audiosamplerate", audioRate);
amfMap.setProperty("audiosamplesize", audioSize);
if(isStereo) {
amfMap.setProperty("stereo", true);
} else {
amfMap.setProperty("stereo", false);
}
amfMap.setProperty("audiocodecid", FlvAudio.AAC);
int size = amfMap.getSize() + metaDataHeader.getSize();
ByteBuffer amfBuffer = ByteBuffer.allocate(size);
amfBuffer.put(metaDataHeader.getBytes());
amfBuffer.put(amfMap.getBytes());
return amfBuffer.array();
}
示例15: addHeader
import java.nio.ByteBuffer; //导入依赖的package包/类
private static void addHeader(ByteBuffer result, String key, List<String> values) {
StringBuilder sb = new StringBuilder();
Iterator<String> iter = values.iterator();
if (!iter.hasNext()) {
return;
}
sb.append(iter.next());
while (iter.hasNext()) {
sb.append(',');
sb.append(iter.next());
}
result.put(key.getBytes(StandardCharsets.ISO_8859_1));
result.put(": ".getBytes(StandardCharsets.ISO_8859_1));
result.put(sb.toString().getBytes(StandardCharsets.ISO_8859_1));
result.put(crlf);
}