本文整理汇总了Java中java.nio.channels.WritableByteChannel类的典型用法代码示例。如果您正苦于以下问题:Java WritableByteChannel类的具体用法?Java WritableByteChannel怎么用?Java WritableByteChannel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WritableByteChannel类属于java.nio.channels包,在下文中一共展示了WritableByteChannel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: validate
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
/**
* Gets a part of the given URL, writes the content into the given channel.
* Fails if the returned HTTP status is not "206 partial content".
*
* @param <IWC> a generic type for any class that implements InterruptibleChannel and WritableByteChannel
* @param url to get
* @param output written with the content of the HTTP response
* @param etag value of the If-Range header
* @param range_start range byte start (inclusive)
* @param range_end range byte end (inclusive)
*
* @return a response (contains the HTTP Headers, the status code, ...)
*
* @throws IOException IO error
* @throws InterruptedException interrupted
* @throws RuntimeException containing the actual exception if it is not an instance of IOException
*/
public <IWC extends InterruptibleChannel & WritableByteChannel>
HttpResponse interruptibleGetRange(String url, final IWC output, String etag, long range_start, long range_end)
throws IOException, InterruptedException
{
HttpGet get = new HttpGet(url);
get.setHeader("If-Range", etag);
get.setHeader("Range", String.format("bytes=%d-%d", range_start, range_end));
// This validator throws an IOException if the response code is not 206 partial content
ResponseValidator val = new ResponseValidator()
{
@Override
public void validate(HttpResponse response) throws HttpException, IOException
{
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT)
{
throw new IOException("Range request does not return partial content");
}
}
};
return interruptibleRequest(get, output, val);
}
示例2: write
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
public void write(WritableByteChannel channel) throws IOException {
logger.config(getLoggingFilename() + ":Writing tag to channel");
byte[] bodyByteBuffer = writeFramesToBuffer().toByteArray();
logger.config(getLoggingFilename() + ":bodybytebuffer:sizebeforeunsynchronisation:" + bodyByteBuffer.length);
//Unsynchronize if option enabled and unsync required
unsynchronization = TagOptionSingleton.getInstance().isUnsyncTags() && ID3Unsynchronization.requiresUnsynchronization(bodyByteBuffer);
if (isUnsynchronization()) {
bodyByteBuffer = ID3Unsynchronization.unsynchronize(bodyByteBuffer);
logger.config(getLoggingFilename() + ":bodybytebuffer:sizeafterunsynchronisation:" + bodyByteBuffer.length);
}
ByteBuffer headerBuffer = writeHeaderToBuffer(0, bodyByteBuffer.length);
channel.write(headerBuffer);
channel.write(ByteBuffer.wrap(bodyByteBuffer));
}
示例3: fastCopy
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
/**
* copy
*
* @param src
* @param dest
* @throws IOException
*/
public static void fastCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException {
final ByteBuffer buffer = ByteBuffer.allocateDirect(8 * 1024);
int count = 0;
while ((count = src.read(buffer)) != -1) {
// LogUtil.d("luaviewp-fastCopy", count, buffer.capacity(), buffer.remaining(), buffer.array().length);
// prepare the buffer to be drained
buffer.flip();
// write to the channel, may block
dest.write(buffer);
// If partial transfer, shift remainder down
// If buffer is empty, same as doing clear()
buffer.compact();
}
// EOF will leave buffer in fill state
buffer.flip();
// make sure the buffer is fully drained.
while (buffer.hasRemaining()) {
dest.write(buffer);
}
}
示例4: sendAck
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
/**
* send a reply-acknowledgement (6,2,3), sends it doing a busy write, the ACK is so small
* that it should always go to the buffer
* @param key
* @param channel
*/
protected void sendAck(SelectionKey key, WritableByteChannel channel, byte[] command, SocketAddress udpaddr) {
try {
ByteBuffer buf = ByteBuffer.wrap(command);
int total = 0;
if (channel instanceof DatagramChannel) {
DatagramChannel dchannel = (DatagramChannel)channel;
//were using a shared channel, document says its thread safe
//TODO check optimization, one channel per thread?
while ( total < command.length ) {
total += dchannel.send(buf, udpaddr);
}
} else {
while ( total < command.length ) {
total += channel.write(buf);
}
}
if (log.isTraceEnabled()) {
log.trace("ACK sent to " +
( (channel instanceof SocketChannel) ?
((SocketChannel)channel).socket().getInetAddress() :
((DatagramChannel)channel).socket().getInetAddress()));
}
} catch ( java.io.IOException x ) {
log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage());
}
}
示例5: readStreamAsStr
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
/**
* 将流转换为字符串
*
* @param is
* @return
* @throws IOException
*/
public static String readStreamAsStr(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
WritableByteChannel dest = Channels.newChannel(bos);
ReadableByteChannel src = Channels.newChannel(is);
ByteBuffer bb = ByteBuffer.allocate(4096);
while (src.read(bb) != -1) {
bb.flip();
dest.write(bb);
bb.clear();
}
src.close();
dest.close();
return new String(bos.toByteArray(), Constants.ENCODING);
}
示例6: ArrayOutputAdapter
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
/**
* Constructs an adapter for the specified channel, output, and byte order.
* If not null, the writable byte channel enables more efficient writes.
* @param channel the writable byte channel; null, if none.
* @param output the data output.
* @param order the byte order.
*/
public ArrayOutputAdapter(
WritableByteChannel channel, DataOutput output, ByteOrder order)
{
_wbc = channel;
_do = output;
_bo = order;
if (_wbc!=null) {
_bb = ByteBuffer.allocateDirect(4096);
} else {
_buffer = new byte[4096];
_bb = ByteBuffer.wrap(_buffer);
}
if (order==ByteOrder.BIG_ENDIAN) {
_bb.order(ByteOrder.BIG_ENDIAN);
} else {
_bb.order(ByteOrder.LITTLE_ENDIAN);
}
_cb = _bb.asCharBuffer();
_sb = _bb.asShortBuffer();
_ib = _bb.asIntBuffer();
_lb = _bb.asLongBuffer();
_fb = _bb.asFloatBuffer();
_db = _bb.asDoubleBuffer();
}
示例7: execute
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
/**
* execute.
* @param cmd - cmd
* @throws IOException - IOException
*/
@Override
public void execute(Command cmd) throws IOException {
Path filePath = Paths.get(cmd.getParam());
if (Files.exists(filePath, LinkOption.NOFOLLOW_LINKS)
&& !Files.isDirectory(filePath) && Files.isReadable(filePath)) {
System.out.println("Uploading...");
ObjectOutputStream oos = new ObjectOutputStream(outputStream);
oos.writeObject(cmd);
oos.flush();
WritableByteChannel rbc = Channels.newChannel(new DataOutputStream(outputStream));
FileInputStream fis = new FileInputStream(cmd.getParam());
fis.getChannel().transferTo(0, Long.MAX_VALUE, rbc);
rbc.close();
System.out.println("Done.");
} else {
System.out.println("Error. Please try again.");
}
}
示例8: sendAck
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
/**
* send a reply-acknowledgement (6,2,3), sends it doing a busy write, the
* ACK is so small that it should always go to the buffer
*
* @param key
* @param channel
*/
protected void sendAck(SelectionKey key, WritableByteChannel channel, byte[] command, SocketAddress udpaddr) {
try {
ByteBuffer buf = ByteBuffer.wrap(command);
int total = 0;
if (channel instanceof DatagramChannel) {
DatagramChannel dchannel = (DatagramChannel) channel;
// were using a shared channel, document says its thread safe
// TODO check optimization, one channel per thread?
while (total < command.length) {
total += dchannel.send(buf, udpaddr);
}
} else {
while (total < command.length) {
total += channel.write(buf);
}
}
if (log.isTraceEnabled()) {
log.trace("ACK sent to "
+ ((channel instanceof SocketChannel) ? ((SocketChannel) channel).socket().getInetAddress()
: ((DatagramChannel) channel).socket().getInetAddress()));
}
} catch (java.io.IOException x) {
log.warn("Unable to send ACK back through channel, channel disconnected?: " + x.getMessage());
}
}
示例9: getContentOutputStream
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
/**
* @see Channels#newOutputStream(java.nio.channels.WritableByteChannel)
*/
public OutputStream getContentOutputStream() throws ContentIOException
{
try
{
WritableByteChannel channel = getWritableChannel();
OutputStream is = new BufferedOutputStream(Channels.newOutputStream(channel));
// done
return is;
}
catch (Throwable e)
{
throw new ContentIOException("Failed to open stream onto channel: \n" +
" writer: " + this,
e);
}
}
示例10: transferTo
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
if (this.byteBufferHeader.hasRemaining()) {
transferred += target.write(this.byteBufferHeader);
return transferred;
} else {
List<ByteBuffer> messageBufferList = this.queryMessageResult.getMessageBufferList();
for (ByteBuffer bb : messageBufferList) {
if (bb.hasRemaining()) {
transferred += target.write(bb);
return transferred;
}
}
}
return 0;
}
示例11: getBox
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
public void getBox(WritableByteChannel os) throws IOException {
ByteBuffer bb = ByteBuffer.allocate(l2i(getSize()));
getHeader(bb);
if (content == null) {
getContent(bb);
if (deadBytes != null) {
deadBytes.rewind();
while (deadBytes.remaining() > 0) {
bb.put(deadBytes);
}
}
} else {
content.rewind();
bb.put(content);
}
bb.rewind();
os.write(bb);
}
示例12: getBox
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
ByteBuffer bb = ByteBuffer.allocate(16);
long size = getSize();
if (isSmallBox(size)) {
IsoTypeWriter.writeUInt32(bb, size);
} else {
IsoTypeWriter.writeUInt32(bb, 1);
}
bb.put(IsoFile.fourCCtoBytes("mdat"));
if (isSmallBox(size)) {
bb.put(new byte[8]);
} else {
IsoTypeWriter.writeUInt64(bb, size);
}
bb.rewind();
writableByteChannel.write(bb);
}
示例13: transferTo
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
@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;
}
示例14: transferTo
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
/**
* This code is more complicated than you would think because we might require multiple
* transferTo invocations in order to transfer a single MessageWithHeader to avoid busy waiting.
*
* The contract is that the caller will ensure position is properly set to the total number
* of bytes transferred so far (i.e. value returned by transfered()).
*/
@Override
public long transferTo(final WritableByteChannel target, final long position) throws IOException {
Preconditions.checkArgument(position == totalBytesTransferred, "Invalid position.");
// Bytes written for header in this call.
long writtenHeader = 0;
if (header.readableBytes() > 0) {
writtenHeader = copyByteBuf(header, target);
totalBytesTransferred += writtenHeader;
if (header.readableBytes() > 0) {
return writtenHeader;
}
}
// Bytes written for body in this call.
long writtenBody = 0;
if (body instanceof FileRegion) {
writtenBody = ((FileRegion) body).transferTo(target, totalBytesTransferred - headerLength);
} else if (body instanceof ByteBuf) {
writtenBody = copyByteBuf((ByteBuf) body, target);
}
totalBytesTransferred += writtenBody;
return writtenHeader + writtenBody;
}
示例15: transferTo
import java.nio.channels.WritableByteChannel; //导入依赖的package包/类
@Override
public long transferTo(WritableByteChannel target, long position)
throws IOException {
if (manageOsCache && readaheadPool != null) {
readaheadRequest = readaheadPool.readaheadStream(identifier, fd,
getPosition() + position, readaheadLength,
getPosition() + getCount(), readaheadRequest);
}
if(this.shuffleTransferToAllowed) {
return super.transferTo(target, position);
} else {
return customShuffleTransfer(target, position);
}
}