Example usage for java.nio ByteBuffer flip

List of usage examples for java.nio ByteBuffer flip

Introduction

In this page you can find the example usage for java.nio ByteBuffer flip.

Prototype

public final Buffer flip() 

Source Link

Document

Flips this buffer.

Usage

From source file:com.msr.dnsdemo.network.DownloadFile.java

public static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
        throws IOException, NullPointerException {
    if (src != null && dest != null) {
        final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
        while (src.read(buffer) != -1) {
            // prepare the buffer to be drained
            buffer.flip();
            // write to the channel, may block
            dest.write(buffer);/*from www . j a  v  a 2 s  . c  om*/
            // 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);
        }
    }
}

From source file:Main.java

public static void readData(SeekableByteChannel seekableChannel, Charset cs) throws IOException {
    ByteBuffer byteBuffer = ByteBuffer.allocate(128);
    String encoding = System.getProperty("file.encoding");
    while (seekableChannel.read(byteBuffer) > 0) {
        byteBuffer.rewind();/*www.  j  a  v a  2s .c o  m*/
        CharBuffer charBuffer = cs.decode(byteBuffer);
        System.out.print(charBuffer);
        byteBuffer.flip();
    }
}

From source file:com.chicm.cmraft.rpc.PacketUtils.java

private static int writeRpc(AsynchronousSocketChannel channel, Message header, Message body, int totalSize)
        throws IOException, InterruptedException, ExecutionException {
    // writing total size so that server can read all request data in one read
    //LOG.debug("total size:" + totalSize);
    long t = System.currentTimeMillis();

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    writeIntToStream(totalSize, bos);// www.jav  a  2  s. c  o  m

    header.writeDelimitedTo(bos);
    if (body != null)
        body.writeDelimitedTo(bos);

    bos.flush();
    byte[] b = bos.toByteArray();
    ByteBuffer buf = ByteBuffer.allocateDirect(totalSize + 4);
    buf.put(b);

    buf.flip();
    channel.write(buf).get();

    if (LOG.isTraceEnabled()) {
        LOG.trace("Write Rpc message to socket, takes " + (System.currentTimeMillis() - t) + " ms, size "
                + totalSize);
        LOG.trace("message:" + body);
    }
    return totalSize;
}

From source file:fi.johannes.kata.ocr.utils.files.CFileOperations.java

public static void writeToFile(ByteBuffer bb, String outputFile) throws IOException {
    bb.flip();
    try (BufferedWriter bw = new BufferedWriter(new PrintWriter(outputFile, "UTF-8"))) {
        CharBuffer charBuffer = StandardCharsets.UTF_8.decode(bb);
        bw.write(charBuffer.toString());
        charBuffer.clear();/*from www.  j a v a 2s  . com*/
    }
}

From source file:ja.centre.util.io.Files.java

public static void copy(String source, String destination) throws IOException {
    FileInputStream fis = null;/* w w  w. jav a  2 s.  c o m*/
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream(source);
        fos = new FileOutputStream(destination);

        FileChannel fic = null;
        FileChannel foc = null;
        try {
            fic = fis.getChannel();
            foc = fos.getChannel();

            ByteBuffer buffer = ByteBuffer.allocate(COPY_BUFFER_SIZE);
            do {
                buffer.flip();
                foc.write(buffer);
                buffer.clear();
            } while (fic.read(buffer) != -1);
        } finally {
            closeQuietly(fic);
            closeQuietly(foc);
        }
    } finally {
        closeQuietly(fis);
        closeQuietly(fos);
    }
}

From source file:com.log4ic.compressor.utils.FileUtils.java

/**
 * ?//from w w w  .  ja  v  a2 s .co m
 *
 * @param content
 * @param filePath
 * @return
 */
public static File writeFile(byte[] content, String filePath) {
    FileOutputStream out = null;
    FileChannel outChannel = null;
    File file = new File(filePath);

    if (file.exists()) {
        file.delete();
    }

    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
    }

    ByteBuffer outBuffer = ByteBuffer.allocate(content.length);
    outBuffer.put(content);
    outBuffer.flip();
    try {
        out = new FileOutputStream(file);

        outChannel = out.getChannel();

        outChannel.write(outBuffer);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outChannel != null) {
            try {
                outChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return file.exists() ? file : null;
}

From source file:com.icloud.framework.core.nio.ByteBufferUtil.java

public static ByteBuffer clone(ByteBuffer o) {
    assert o != null;

    if (o.remaining() == 0)
        return ByteBuffer.wrap(ArrayUtils.EMPTY_BYTE_ARRAY);

    ByteBuffer clone = ByteBuffer.allocate(o.remaining());

    if (o.isDirect()) {
        for (int i = o.position(); i < o.limit(); i++) {
            clone.put(o.get(i));/*w  ww . j ava 2s  .c  om*/
        }
        clone.flip();
    } else {
        System.arraycopy(o.array(), o.arrayOffset() + o.position(), clone.array(), 0, o.remaining());
    }

    return clone;
}

From source file:ja.lingo.engine.util.EngineFiles.java

private static void appendFile(String fileName, FileOutputStream fos, boolean prependWithLength)
        throws IOException {
    FileInputStream fis = new FileInputStream(fileName);
    FileChannel fic = fis.getChannel();
    FileChannel foc = fos.getChannel();

    ByteBuffer buffer = ByteBuffer.allocate(COPY_BUFFER_SIZE);

    // put header: length (1 int = 4 bytes)
    if (prependWithLength) {
        buffer.putInt((int) new File(fileName).length());
    }/*from www . jav a 2  s .  com*/

    // put body
    do {
        buffer.flip();
        foc.write(buffer);
        buffer.clear();
    } while (fic.read(buffer) != -1);
    fic.close();
    // NOTE: do not close 'foc'

    Files.delete(fileName);
}

From source file:StreamUtil.java

/**
 * Copies the content read from InputStream to OutputStream. Uses the NIO Channels to copy.
 * @param is The InputStream that is read.
 * @param os The OutputStream where the data is written.
 * @throws IOException//from  w w  w  .  j  a v  a2 s . c o m
 */
public static void copy(final InputStream is, final OutputStream os) throws IOException {
    final ReadableByteChannel inChannel = Channels.newChannel(is);
    final WritableByteChannel outChannel = Channels.newChannel(os);

    try {
        final ByteBuffer buffer = ByteBuffer.allocate(65536);
        while (true) {
            int bytesRead = inChannel.read(buffer);
            if (bytesRead == -1)
                break;
            buffer.flip();
            while (buffer.hasRemaining())
                outChannel.write(buffer);
            buffer.clear();
        }
    } finally {
        try {
            inChannel.close();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
        try {
            outChannel.close();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.offbynull.portmapper.natpmp.NatPmpDiscovery.java

private static Set<InetAddress> discoverGateways() throws InterruptedException, IOException {
    final Set<InetAddress> foundGateways = Collections.synchronizedSet(new HashSet<InetAddress>());
    Set<InetAddress> potentialGateways = NetworkUtils.getPotentialGatewayAddresses(); // port 5351

    DatagramChannel unicastChannel = null;
    try {/*from   w  ww .j  a  v  a 2  s.com*/
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(Collections.singletonList(unicastChannel));
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                new ExternalAddressNatPmpResponse(packet); // should error out if not valid

                foundGateways.add(sourceAddress.getAddress());
            }
        });

        ByteBuffer outBuf = ByteBuffer.allocate(16);
        ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest();
        eanpr.dump(outBuf);

        outBuf.flip();

        for (InetAddress potentialGateway : potentialGateways) {
            communicator.send(unicastChannel, new InetSocketAddress(potentialGateway, 5351),
                    outBuf.asReadOnlyBuffer());
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    return new HashSet<>(foundGateways);
}