下面列出了java.nio.channels.WritableByteChannel#write() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static int writeVInt(WritableByteChannel wbc, int value) throws IOException {
ByteBuffer bb = ByteBuffer.allocate(8);
while (true) {
if ((value & ~0x7F) == 0) {
bb.put((byte) value);
break;
} else {
bb.put((byte) ((value & 0x7F) | 0x80));
value >>>= 7;
}
}
bb.flip();
wbc.write(bb);
return bb.limit();
}
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
if (this.byteBufferHeader.hasRemaining()) {
transfered += target.write(this.byteBufferHeader);
return transfered;
}
else {
List<ByteBuffer> messageBufferList = this.getMessageResult.getMessageBufferList();
for (ByteBuffer bb : messageBufferList) {
if (bb.hasRemaining()) {
transfered += target.write(bb);
return transfered;
}
}
}
return 0;
}
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
if (this.byteBufferHeader.hasRemaining()) {
transfered += target.write(this.byteBufferHeader);
return transfered;
} else {
List<ByteBuffer> messageBufferList = this.queryMessageResult.getMessageBufferList();
for (ByteBuffer bb : messageBufferList) {
if (bb.hasRemaining()) {
transfered += target.write(bb);
return transfered;
}
}
}
return 0;
}
static InputStream copyRequestBody(ODataRequest request) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
InputStream input = request.getBody();
if (input != null) {
try {
ByteBuffer inBuffer = ByteBuffer.allocate(8192);
ReadableByteChannel ic = Channels.newChannel(input);
WritableByteChannel oc = Channels.newChannel(buffer);
while (ic.read(inBuffer) > 0) {
inBuffer.flip();
oc.write(inBuffer);
inBuffer.rewind();
}
return new ByteArrayInputStream(buffer.toByteArray());
} catch (IOException e) {
throw new ODataRuntimeException("Error on reading request content");
}
}
return null;
}
public void getBox(WritableByteChannel os) throws IOException {
for (ParsableBox replacer : replacers) {
replacer.getBox(os);
}
ByteBuffer header = ByteBuffer.allocate(8);
IsoTypeWriter.writeUInt32(header, 8 + data.limit());
header.put(TYPE.getBytes());
((Buffer)header).rewind();
os.write(header);
((Buffer)header).rewind();
((Buffer)data).rewind();
os.write(data);
((Buffer)data).rewind();
}
@Override
public long writeTo(int index, WritableByteChannel channel, long relativeOffset, long maxSize) throws IOException {
buffers.get(index).position((int) relativeOffset);
buffers.get(index).limit((int) Math.min(buffers.get(index).limit(), relativeOffset + maxSize));
int written = channel.write(buffers.get(index));
buffers.get(index).clear();
return written;
}
private boolean StartInstance(Socket socket, com.riiablo.net.packet.msi.MSI packet) throws IOException {
Gdx.app.debug(TAG, "Starting instance...");
try {
File outFile = new File("D2GS.tmp");
ProcessBuilder processBuilder = new ProcessBuilder("java", "-jar", "server/d2gs/build/libs/d2gs-1.0.jar");
processBuilder.redirectOutput(ProcessBuilder.Redirect.to(outFile));
processBuilder.redirectError(ProcessBuilder.Redirect.to(outFile));
Process process = processBuilder.start();
instances.add(process);
} catch (Throwable t) {
Gdx.app.error(TAG, t.getMessage(), t);
}
int ip = 2130706433; // 127.0.0.1
short port = 6114;
FlatBufferBuilder builder = new FlatBufferBuilder();
StartInstance.startStartInstance(builder);
StartInstance.addResult(builder, Result.SUCCESS);
StartInstance.addIp(builder, ip);
StartInstance.addPort(builder, port);
int startInstanceOffset = StartInstance.endStartInstance(builder);
int id = com.riiablo.net.packet.msi.MSI.createMSI(builder, MSIData.StartInstance, startInstanceOffset);
builder.finish(id);
ByteBuffer data = builder.dataBuffer();
OutputStream out = socket.getOutputStream();
WritableByteChannel channel = Channels.newChannel(out);
channel.write(data);
Gdx.app.debug(TAG, "Returning instance at " + InetAddress.getByAddress(ByteBuffer.allocate(4).putInt(ip).array()));
return true;
}
private void writeWithHeader(WritableByteChannel channel, byte[] body) throws IOException {
synchronized (writeDataLock) {
writeHeader.clear();
writeHeader.putInt(body.length);
writeHeader.flip();
channel.write(writeHeader);
channel.write(ByteBuffer.wrap(body));
}
}
@Test
public void reupload_failure_cacheTooSmall_singleWrite_singleChunk() throws Exception {
byte[] testData = new byte[MediaHttpUploader.MINIMUM_CHUNK_SIZE];
new Random().nextBytes(testData);
int uploadChunkSize = testData.length;
int uploadCacheSize = testData.length / 2;
MockHttpTransport transport =
mockTransport(
emptyResponse(HttpStatusCodes.STATUS_CODE_NOT_FOUND),
resumableUploadResponse(BUCKET_NAME, OBJECT_NAME),
jsonErrorResponse(ErrorResponses.GONE));
AsyncWriteChannelOptions writeOptions =
AsyncWriteChannelOptions.builder()
.setUploadChunkSize(uploadChunkSize)
.setUploadCacheSize(uploadCacheSize)
.build();
GoogleCloudStorage gcs =
mockedGcs(GCS_OPTIONS.toBuilder().setWriteChannelOptions(writeOptions).build(), transport);
WritableByteChannel writeChannel = gcs.create(new StorageResourceId(BUCKET_NAME, OBJECT_NAME));
writeChannel.write(ByteBuffer.wrap(testData));
IOException writeException = assertThrows(IOException.class, writeChannel::close);
assertThat(writeException).hasCauseThat().isInstanceOf(GoogleJsonResponseException.class);
assertThat(writeException).hasCauseThat().hasMessageThat().startsWith("410");
}
protected void writeByteBufferToChannel(ByteBuffer src, WritableByteChannel outputChannel)
throws MkvElementVisitException {
src.rewind();
int size = src.remaining();
try {
int numBytes = outputChannel.write(src);
Validate.isTrue(size == numBytes, "Output channel wrote " + size + " bytes instead of " + numBytes);
} catch (IOException e) {
throw new MkvElementVisitException("Writing to output channel failed", e);
} finally {
src.rewind();
}
}
public void writeValue(WritableByteChannel channel) {
final ByteBuffer buffer = toByteBuffer();
int k;
try {
do {
k = channel.write(buffer);
} while (k > 0 && buffer.hasRemaining());
if (buffer.hasRemaining()) {
throw new StoreException("wrote incomplete germ");
}
} catch (IOException cause) {
throw new StoreException(cause);
}
}
public void send(Packet packet) throws IOException {
if (!socket.isConnected()) return;
WritableByteChannel out = Channels.newChannel(socket.getOutputStream());
packet.buffer.mark();
out.write(packet.buffer);
packet.buffer.reset();
if ((connected & (1 << id)) == 0 && packet.data.dataType() == D2GSData.Connection) {
connected |= (1 << id);
}
}
@Override
public long writeTo(int index, WritableByteChannel channel, long relativeOffset, long maxSize)
throws IOException {
buffer.position(messageList.get(index).position + (int) relativeOffset);
byte[] toReturn = new byte[Math.min(messageList.get(index).size, (int) maxSize)];
buffer.get(toReturn);
return channel.write(ByteBuffer.wrap(toReturn));
}
private static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
throws IOException {
final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
while (src.read(buffer) != -1) {
buffer.flip();
dest.write(buffer);
buffer.compact();
}
buffer.flip();
while (buffer.hasRemaining()) {
dest.write(buffer);
}
}
/**
* Append the given buffer to this data
*
* @param buffer The buffer
* @throws IOException If an IO error occurs
*/
void append(ByteBuffer buffer) throws IOException
{
@SuppressWarnings("resource")
WritableByteChannel writableByteChannel =
Channels.newChannel(baos);
writableByteChannel.write(buffer.slice());
}
public void writeTo(WritableByteChannel channel) throws java.io.IOException {
channel.write(vtte.duplicate());
}
private static void writeContents(WritableByteChannel out, ByteBuffer data) throws IOException {
while (data.hasRemaining())
out.write(data);
}
public final long transferTo(WritableByteChannel ch) throws IOException {
return ch.write(buffer);
}
@Override
public int transferTo(WritableByteChannel sbc) throws IOException {
return sbc.write(delegate);
}
/**
* Writes the entire remaining contents of the buffer to the channel. May complete in one operation, but the
* documentation is vague, so this keeps going until we are sure.
*
* @param buffer the data to be written
* @param channel the channel to which we want to write data
*
* @throws IOException if there is a problem writing to the channel
*/
public static void writeFully(ByteBuffer buffer, WritableByteChannel channel) throws IOException {
while (buffer.hasRemaining()) {
channel.write(buffer);
}
}