Example usage for java.nio ByteBuffer wrap

List of usage examples for java.nio ByteBuffer wrap

Introduction

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

Prototype

public static ByteBuffer wrap(byte[] array, int start, int len) 

Source Link

Document

Creates a new byte buffer by wrapping the given byte array.

Usage

From source file:Util.java

public void write(File dest, InputStream in) {
    FileChannel channel = null;/*from w w w  . jav  a  2  s . com*/
    try {
        channel = new FileOutputStream(dest).getChannel();
    } catch (FileNotFoundException e) {
        System.out.println(e);
    }
    try {
        int byteCount = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;
        while ((bytesRead = in.read(buffer)) != -1) {
            ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, 0, bytesRead);
            channel.write(byteBuffer);
            byteCount += bytesRead;
        }

    } catch (IOException e) {
        System.out.println(e);
    } finally {

        try {
            if (channel != null) {
                channel.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.cloud.utils.NumbersUtil.java

public static long bytesToLong(byte b[], int pos) {
    return ByteBuffer.wrap(b, pos, 8).getLong();
}

From source file:Main.java

public static void copyInputStreamToFile(InputStream inputStream, File file) throws IOException {
    FileOutputStream fileOutputStream = null;
    FileChannel fileChannel = null;
    try {/*from  w  w  w .  java2  s .  co  m*/
        fileOutputStream = new FileOutputStream(file);
        fileChannel = fileOutputStream.getChannel();
        byte[] bArr = new byte[4096];
        while (true) {
            int read = inputStream.read(bArr);
            if (read <= 0) {
                break;
            }
            fileChannel.write(ByteBuffer.wrap(bArr, SYSTEM_ROOT_STATE_DISABLE, read));
        }

    } catch (Throwable throwable) {
        throwable.printStackTrace();
    } finally {

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (fileChannel != null) {
            try {
                fileChannel.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (Exception e22) {
                e22.printStackTrace();
            }
        }
    }
}

From source file:Main.java

public static void copyInputStreamToFile(InputStream inputStream, File file) throws IOException {
    FileOutputStream fileOutputStream = null;
    Throwable th;//from  w  ww.j ava  2  s . c  o m
    FileChannel fileChannel = null;
    try {
        fileOutputStream = new FileOutputStream(file);
        try {
            fileChannel = fileOutputStream.getChannel();
            byte[] bArr = new byte[4096];
            while (true) {
                int read = inputStream.read(bArr);
                if (read <= 0) {
                    break;
                }
                fileChannel.write(ByteBuffer.wrap(bArr, SYSTEM_ROOT_STATE_DISABLE, read));
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (fileChannel != null) {
                try {
                    fileChannel.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (Exception e22) {
                    e22.printStackTrace();
                }
            }
        } catch (Throwable th2) {
            th = th2;
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e3) {
                    e3.printStackTrace();
                }
            }
            if (fileChannel != null) {
                try {
                    fileChannel.close();
                } catch (Exception e4) {
                    e4.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (Exception e42) {
                    e42.printStackTrace();
                }
            }
            throw th;
        }
    } catch (Throwable th3) {
        th = th3;
        Object obj = fileChannel;
        if (inputStream != null) {
            inputStream.close();
        }
        if (fileChannel != null) {
            fileChannel.close();
        }
        if (fileOutputStream != null) {
            fileOutputStream.close();
        }

    }
}

From source file:com.easemob.dataexport.utils.ConversionUtils.java

/**
 * @param uuid/*from w  ww.  j  a  v  a 2s.c o  m*/
 * @param offset
 * @return
 */
public static UUID uuid(byte[] uuid, int offset) {
    ByteBuffer bb = ByteBuffer.wrap(uuid, offset, 16);
    return new UUID(bb.getLong(), bb.getLong());
}

From source file:neembuu.httpserver.VFileEntity.java

@Override
public InputStream getContent() throws IOException, IllegalStateException {
    return new InputStream() {
        long pos = startingOffset;

        @Override//from www .j  a v  a2 s  . co  m
        public int read() throws IOException {
            throw new IllegalStateException("This is not used.");
        }

        @Override
        public int read(byte[] b) throws IOException {
            return read(b, 0, b.length); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            ByteBuffer bb = ByteBuffer.wrap(b, 0, len);
            BlockingReadRequest brr = new BlockingReadRequest(bb, pos);
            try {
                af.read(new SimpleReadRequest(bb, pos));
            } catch (Exception a) {
                IOException ioe = new IOException();
                ioe.addSuppressed(a);
            }
            int read = brr.read();
            pos += read;
            return read;
        }

    };
}

From source file:StreamUtil.java

/**
 * Reads the stream and generates a String content using the charset specified.
 * Stream will be closed at the end of the operation.
 * @param in InputStream as the input.//from   w  ww  .j a  v  a2  s  .c  om
 * @param charset The charset to use to create the String object.
 * @return The output String.
 * @throws IOException
 */
public static String inputStream2String(final InputStream is, final Charset charset) throws IOException {
    try {
        StringBuilder out = new StringBuilder();
        byte[] b = new byte[4096];
        byte[] savedBytes = new byte[1];
        boolean hasSavedBytes = false;
        CharsetDecoder decoder = charset.newDecoder();
        for (int n; (n = is.read(b)) != -1;) {
            if (hasSavedBytes) {
                byte[] bTmp = new byte[savedBytes.length + b.length];
                System.arraycopy(savedBytes, 0, bTmp, 0, savedBytes.length);
                System.arraycopy(b, 0, bTmp, savedBytes.length, b.length);
                b = bTmp;
                hasSavedBytes = false;
                n = n + savedBytes.length;
            }

            CharBuffer charBuffer = decodeHelper(b, n, charset);
            if (charBuffer == null) {
                int nrOfChars = 0;
                while (charBuffer == null) {
                    nrOfChars++;
                    charBuffer = decodeHelper(b, n - nrOfChars, charset);
                    if (nrOfChars > 10 && nrOfChars < n) {
                        try {
                            charBuffer = decoder.decode(ByteBuffer.wrap(b, 0, n));
                        } catch (MalformedInputException ex) {
                            throw new IOException(
                                    "File not in supported encoding (" + charset.displayName() + ")", ex);
                        }
                    }
                }
                savedBytes = new byte[nrOfChars];
                hasSavedBytes = true;
                for (int i = 0; i < nrOfChars; i++) {
                    savedBytes[i] = b[n - nrOfChars + i];
                }
            }

            charBuffer.rewind(); // Bring the buffer's pointer to 0
            out.append(charBuffer.toString());
        }
        if (hasSavedBytes) {
            try {
                CharBuffer charBuffer = decoder.decode(ByteBuffer.wrap(savedBytes, 0, savedBytes.length));
            } catch (MalformedInputException ex) {
                throw new IOException("File not in supported encoding (" + charset.displayName() + ")", ex);
            }
        }
        return out.toString();
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.alibaba.otter.shared.common.utils.ByteUtils.java

public static int bytes2int(byte[] data, int offset) {
    ByteBuffer buffer = ByteBuffer.wrap(data, offset, 4);
    return buffer.getInt();
}

From source file:com.github.cat.yum.store.base.RpmScan.java

@SuppressWarnings("unused")
private RpmFormat getRpmFormat() throws IOException {
    InputStream sourceStream = null;
    try {//ww  w.  j av a 2 s.c  o  m
        sourceStream = new FileInputStream(this.rpm);

        RpmFormat rpmFormat = new RpmFormat();
        ReadableChannelWrapper in = getReadableChannel(sourceStream);

        Format format = new Format();
        ChannelWrapper.Key<Integer> headerStartKey = in.start();

        ChannelWrapper.Key<Integer> lead = in.start();
        format.getLead().read(in);

        ChannelWrapper.Key<Integer> signature = in.start();
        int count = format.getSignature().read(in);
        AbstractHeader.Entry<?> sigEntry = format.getSignature().getEntry(Signature.SignatureTag.SIGNATURES);
        int expected = sigEntry == null ? 0
                : ByteBuffer.wrap((byte[]) (byte[]) sigEntry.getValues(), 8, 4).getInt() / -16;

        Integer headerStartPos = (Integer) in.finish(headerStartKey);
        format.getHeader().setStartPos(headerStartPos.intValue());
        ChannelWrapper.Key<Integer> headerKey = in.start();
        count = format.getHeader().read(in);
        AbstractHeader.Entry<?> immutableEntry = format.getHeader().getEntry(Header.HeaderTag.HEADERIMMUTABLE);
        expected = immutableEntry == null ? 0
                : ByteBuffer.wrap((byte[]) (byte[]) immutableEntry.getValues(), 8, 4).getInt() / -16;
        Integer headerLength = (Integer) in.finish(headerKey);
        format.getHeader().setEndPos(headerStartPos.intValue() + headerLength.intValue());

        rpmFormat.headerStart = headerStartPos.intValue();
        rpmFormat.headerEnd = (headerStartPos.intValue() + headerLength.intValue());
        rpmFormat.format = format;

        return rpmFormat;
    } finally {
        try {
            sourceStream.close();
        } catch (IOException ignore) {

        }
    }
}

From source file:edu.umass.cs.reconfiguration.reconfigurationutils.ReconfigurationPacketDemultiplexer.java

@Override
public JSONObject processHeader(byte[] msg, NIOHeader header) {
    long t = System.nanoTime();
    int type;/*  www  .ja va2 s.  c om*/
    JSONObject json = null;
    log.log(Level.FINEST, "{0} processHeader received message with header {1}", new Object[] { this, header });
    if (msg.length >= Integer.BYTES
            && ReconfigurationPacket.PacketType.intToType
                    .containsKey(type = ByteBuffer.wrap(msg, 0, 4).getInt())
            && JSONPacket.couldBeJSON(msg, Integer.BYTES)
            && type != PacketType.REPLICABLE_CLIENT_REQUEST.getInt()) {
        json = super.processHeader(msg, Integer.BYTES, header, true);
        if (json != null) {
            if (Util.oneIn(50))
                DelayProfiler.updateDelayNano("processHeader", t);
            return json;
        }
    } else if (!BYTEIFICATION && JSONPacket.couldBeJSON(msg)
            && (json = super.processHeader(msg, header, true)) != null) {
        return json;
    }
    // else prefix msg with addresses
    byte[] stamped = new byte[NIOHeader.BYTES + msg.length];
    ByteBuffer bbuf = ByteBuffer.wrap(stamped);
    bbuf.put(header.toBytes());
    bbuf.put(msg);
    if (Util.oneIn(50))
        DelayProfiler.updateDelayNano("processHeader", t);
    return new JSONMessenger.JSONObjectWrapper(stamped);
}