List of usage examples for java.nio ByteBuffer flip
public final Buffer flip()
From source file:org.apache.ofbiz.base.util.UtilIO.java
/** Convert a byte array to a string, consistently uses \n line * endings in java. The conversion is limited to the specified * offset/length pair, and uses the requested {@link Charset * charset} to decode the bytes./*w w w . j a va 2s. com*/ * * @param bytes the array of bytes to convert * @param offset the start of the conversion * @param length how many bytes to convert * @param charset the charset to use to convert the raw bytes * @return the converted string, with platform line endings converted * to \n */ public static final String readString(byte[] bytes, int offset, int length, Charset charset) throws IOException { ByteBuffer buf = ByteBuffer.allocate(length); buf.put(bytes, offset, length); buf.flip(); return filterLineEndings(new StringBuilder(charset.decode(buf).toString())).toString(); }
From source file:com.offbynull.portmapper.natpmp.NatPmpDiscovery.java
private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways) throws IOException, InterruptedException { Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses(); List<DatagramChannel> channels = new ArrayList<>(); final Map<DatagramChannel, InetAddress> bindMap = Collections .synchronizedMap(new HashMap<DatagramChannel, InetAddress>()); final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections .synchronizedMap(new HashMap<InetAddress, InetAddress>()); try {//from w w w . j ava 2s. co m for (InetAddress localAddress : localAddresses) { DatagramChannel unicastChannel = null; try { unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0)); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); throw ioe; } channels.add(unicastChannel); bindMap.put(unicastChannel, localAddress); } } catch (IOException ioe) { for (DatagramChannel channel : channels) { IOUtils.closeQuietly(channel); } throw ioe; } UdpCommunicator communicator = null; try { communicator = new UdpCommunicator(channels); 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 InetAddress localAddress = bindMap.get(channel); if (localAddress == null) { return; } localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress()); } }); ByteBuffer outBuf = ByteBuffer.allocate(16); ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest(); eanpr.dump(outBuf); outBuf.flip(); for (DatagramChannel channel : bindMap.keySet()) { for (InetAddress gateway : gateways) { communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer()); } } Thread.sleep(5000L); } finally { if (communicator != null) { communicator.stopAsync().awaitTerminated(); } } return new HashMap<>(localAddrToGatewayAddrMap); }
From source file:org.osiam.tests.performance.tools.TestDataCreation.java
private static ByteBuffer getBigByteBuffer(Integer countCurrentUser) { String userId = countCurrentUser.toString(); byte[] bytes = new byte[userId.length() + MIN_COUNT_BYTE_BUFFER]; int actPosition; // first comes the id char[] userChars = userId.toCharArray(); for (int count = 0; count < userChars.length; count++) { bytes[count] = (byte) userChars[count]; }//from www . j a v a 2s. co m actPosition = userChars.length; // now we add random bytes Random random = new Random(); String allowedChars = "0123456789abcdefghijklmnopqrstuvwxyz"; int max = allowedChars.length(); for (int i = 0; i < MIN_COUNT_BYTE_BUFFER; i++) { int value = random.nextInt(max); bytes[actPosition++] = (byte) allowedChars.charAt(value); } ByteBuffer ret = ByteBuffer.wrap(new byte[bytes.length]); ret.put(bytes); ret.flip(); return ret; }
From source file:com.liveramp.commons.util.BytesUtils.java
public static ByteBuffer byteBufferDeepCopy(ByteBuffer src, ByteBuffer dst) { if (dst == null || dst.capacity() < src.remaining()) { dst = byteBufferDeepCopy(src);/*from w ww .j a va2s. co m*/ } else { dst.rewind(); dst.limit(src.remaining()); dst.put(src.slice()); dst.flip(); } return dst; }
From source file:com.googlecode.jcimd.TextMessageUserDataFactory.java
private static byte[] encodeAs(Charset charset, String textMessage) { CharsetEncoder encoder = charset.newEncoder(); ByteBuffer byteBuffer = ByteBuffer .allocate(textMessage.length() * (int) Math.ceil(encoder.maxBytesPerChar())); encoder.encode(CharBuffer.wrap(textMessage), byteBuffer, true); byte[] bytes = new byte[byteBuffer.position()]; byteBuffer.flip(); byteBuffer.get(bytes);//www.j a v a 2 s. c o m return bytes; }
From source file:Main.java
public static void copy(ReadableByteChannel in, WritableByteChannel out) throws IOException { // First, we need a buffer to hold blocks of copied bytes. ByteBuffer buffer = ByteBuffer.allocateDirect(32 * 1024); // Now loop until no more bytes to read and the buffer is empty while (in.read(buffer) != -1 || buffer.position() > 0) { // The read() call leaves the buffer in "fill mode". To prepare // to write bytes from the bufferwe have to put it in "drain mode" // by flipping it: setting limit to position and position to zero buffer.flip(); // Now write some or all of the bytes out to the output channel out.write(buffer);/*from w w w. jav a2 s . c o m*/ // Compact the buffer by discarding bytes that were written, // and shifting any remaining bytes. This method also // prepares the buffer for the next call to read() by setting the // position to the limit and the limit to the buffer capacity. buffer.compact(); } }
From source file:com.unister.semweb.drums.TestUtils.java
/** * Reads from the given numbe of elements (<code>numberOfElementsToRead</code>) from the given file from the * beginning.//from www . j a va 2 s .com */ public static List<DummyKVStorable> readFrom(String filename, int numberOfElementsToRead) throws Exception { HeaderIndexFile<DummyKVStorable> file = new HeaderIndexFile<DummyKVStorable>(filename, AccessMode.READ_ONLY, 1, TestUtils.gp); ByteBuffer dataBuffer = ByteBuffer.allocate(numberOfElementsToRead * TestUtils.gp.getElementSize()); file.read(0, dataBuffer); dataBuffer.flip(); List<DummyKVStorable> readData = new ArrayList<DummyKVStorable>(); while (dataBuffer.position() < dataBuffer.limit()) { byte[] oneLinkData = new byte[TestUtils.gp.getElementSize()]; dataBuffer.get(oneLinkData); DummyKVStorable oneDate = TestUtils.gp.getPrototype().fromByteBuffer(ByteBuffer.wrap(oneLinkData)); readData.add(oneDate); } file.close(); return readData; }
From source file:Main.java
public static boolean fileCopy(File srcFile, File dstFile) { int length = 1048891; FileChannel inC = null;/*from ww w . j a v a 2 s .com*/ FileChannel outC = null; try { FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(dstFile); inC = in.getChannel(); outC = out.getChannel(); ByteBuffer b = null; while (inC.position() < inC.size()) { if ((inC.size() - inC.position()) < length) { length = (int) (inC.size() - inC.position()); } else { length = 1048891; } b = ByteBuffer.allocateDirect(length); inC.read(b); b.flip(); outC.write(b); outC.force(false); } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (inC != null && inC.isOpen()) { inC.close(); } if (outC != null && outC.isOpen()) { outC.close(); } } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.discovery.darchrow.io.IOWriteUtil.java
/** * NIO API ?? ()./* w w w . jav a 2s .co m*/ * * @param bufferLength * the buffer length * @param inputStream * the input stream * @param outputStream * the output stream * @since 1.0.8 * @since jdk1.4 */ private static void writeUseNIO(int bufferLength, InputStream inputStream, OutputStream outputStream) { int i = 0; int sumSize = 0; int j = 0; ///2 //As creme de la creme with regard to performance, you could use NIO Channels and ByteBuffer. ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream); WritableByteChannel writableByteChannel = Channels.newChannel(outputStream); ByteBuffer byteBuffer = ByteBuffer.allocate(bufferLength); try { while (readableByteChannel.read(byteBuffer) != -1) { byteBuffer.flip(); j = writableByteChannel.write(byteBuffer); sumSize += j; byteBuffer.clear(); i++; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Write data over,sumSize:[{}],bufferLength:[{}],loopCount:[{}]", FileUtil.formatSize(sumSize), bufferLength, i); } } catch (IOException e) { throw new UncheckedIOException(e); } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(writableByteChannel); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(readableByteChannel); } }
From source file:divconq.util.IOUtil.java
public static Memory readEntireFileToMemory(Path file) { try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ)) { Memory mem = new Memory(); // TODO improve mem to read right from channel... ByteBuffer bb = ByteBuffer.allocate(4096); int amt = ch.read(bb); while (amt != -1) { bb.flip(); mem.write(bb);// w w w . j av a 2 s . c o m bb.clear(); amt = ch.read(bb); } mem.setPosition(0); return mem; } catch (IOException x) { } return null; }