Example usage for java.nio ByteBuffer put

List of usage examples for java.nio ByteBuffer put

Introduction

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

Prototype

public ByteBuffer put(ByteBuffer src) 

Source Link

Document

Writes all the remaining bytes of the src byte buffer to this buffer's current position, and increases both buffers' position by the number of bytes copied.

Usage

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

public static void createChunksByRowsAndBytes(String inputFile, String outputFolder, int bufferSize, int rows)
        throws FileNotFoundException, IOException {
    File f = new File(inputFile);
    String filename = f.getName();
    BufferedReader bw = new BufferedReader(new FileReader(f));
    ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
    int j = 0;/*from  w  w  w  .  j  av a  2s.c  o m*/
    for (int i = 0; i <= rows; i++) {
        String lineStr = bw.readLine();
        if (lineStr != null) {
            byte[] line = lineStr.getBytes(StandardCharsets.UTF_8);
            if (i == rows) {
                String outputfile = outputFolder + j + "-" + filename;
                writeToFile(buffer, outputfile);
                buffer.clear();
                j++;
                i = 0;
            }
            buffer.put(line);
            buffer.put(System.getProperty("line.separator").getBytes(StandardCharsets.UTF_8));
        } else {
            break;
        }
    }
}

From source file:com.healthmarketscience.jackcess.impl.OleUtil.java

/**
 * Creates a new OlBlob instance using the given information.
 *//*w w w . ja  v a 2s . co  m*/
public static OleBlob createBlob(OleBlob.Builder oleBuilder) throws IOException {
    try {

        if (!WRITEABLE_TYPES.contains(oleBuilder.getType())) {
            throw new IllegalArgumentException(
                    "Cannot currently create ole values of type " + oleBuilder.getType());
        }

        long contentLen = oleBuilder.getContentLength();
        byte[] contentBytes = oleBuilder.getBytes();
        InputStream contentStream = oleBuilder.getStream();
        byte[] packageStreamHeader = NO_DATA;
        byte[] packageStreamFooter = NO_DATA;

        switch (oleBuilder.getType()) {
        case LINK:
            packageStreamHeader = writePackageStreamHeader(oleBuilder);

            // link "content" is file path
            contentBytes = getZeroTermStrBytes(oleBuilder.getFilePath());
            contentLen = contentBytes.length;
            break;

        case SIMPLE_PACKAGE:
            packageStreamHeader = writePackageStreamHeader(oleBuilder);
            packageStreamFooter = writePackageStreamFooter(oleBuilder);
            break;

        case OTHER:
            // nothing more to do
            break;
        default:
            throw new RuntimeException("unexpected type " + oleBuilder.getType());
        }

        long payloadLen = packageStreamHeader.length + packageStreamFooter.length + contentLen;
        byte[] packageHeader = writePackageHeader(oleBuilder, payloadLen);

        long totalOleLen = packageHeader.length + PACKAGE_FOOTER.length + payloadLen;
        if (totalOleLen > DataType.OLE.getMaxSize()) {
            throw new IllegalArgumentException(
                    "Content size of " + totalOleLen + " is too large for ole column");
        }

        byte[] oleBytes = new byte[(int) totalOleLen];
        ByteBuffer bb = PageChannel.wrap(oleBytes);
        bb.put(packageHeader);
        bb.put(packageStreamHeader);

        if (contentLen > 0L) {
            if (contentBytes != null) {
                bb.put(contentBytes);
            } else {
                byte[] buf = new byte[8192];
                int numBytes = 0;
                while ((numBytes = contentStream.read(buf)) >= 0) {
                    bb.put(buf, 0, numBytes);
                }
            }
        }

        bb.put(packageStreamFooter);
        bb.put(PACKAGE_FOOTER);

        return parseBlob(oleBytes);

    } finally {
        ByteUtil.closeQuietly(oleBuilder.getStream());
    }
}

From source file:com.glaf.core.util.ByteBufferUtils.java

/**
 * @return a new copy of the data in @param buffer USUALLY YOU SHOULD USE
 *         ByteBuffer.duplicate() INSTEAD, which creates a new Buffer (so
 *         you can mutate its position without affecting the original)
 *         without copying the underlying array.
 *//*from  w  ww  . j  a v  a2  s . c  om*/
public static ByteBuffer clone(ByteBuffer buffer) {
    assert buffer != null;

    if (buffer.remaining() == 0)
        return EMPTY_BYTE_BUFFER;

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

    if (buffer.hasArray()) {
        System.arraycopy(buffer.array(), buffer.arrayOffset() + buffer.position(), clone.array(), 0,
                buffer.remaining());
    } else {
        clone.put(buffer.duplicate());
        clone.flip();
    }

    return clone;
}

From source file:com.healthmarketscience.jackcess.impl.OleUtil.java

private static byte[] writePackageStreamHeader(OleBlob.Builder oleBuilder) {

    byte[] fileNameBytes = getZeroTermStrBytes(oleBuilder.getFileName());
    byte[] filePathBytes = getZeroTermStrBytes(oleBuilder.getFilePath());

    int headerLen = 6 + fileNameBytes.length + filePathBytes.length;

    if (oleBuilder.getType() == ContentType.SIMPLE_PACKAGE) {

        headerLen += 8 + filePathBytes.length;

    } else {/*from  w w  w. j a  va2 s .c  o  m*/

        headerLen += 2;
    }

    byte[] headerBytes = new byte[headerLen];
    ByteBuffer bb = PageChannel.wrap(headerBytes);
    bb.putShort((short) PACKAGE_STREAM_SIGNATURE);
    bb.put(fileNameBytes);
    bb.put(filePathBytes);

    if (oleBuilder.getType() == ContentType.SIMPLE_PACKAGE) {
        bb.putInt(PS_EMBEDDED_FILE);
        bb.putInt(filePathBytes.length);
        bb.put(filePathBytes, 0, filePathBytes.length);
        bb.putInt((int) oleBuilder.getContentLength());
    } else {
        bb.putInt(PS_LINKED_FILE);
        bb.putShort((short) LINK_HEADER);
    }

    return headerBytes;
}

From source file:com.healthmarketscience.jackcess.impl.IndexImpl.java

/**
 * Writes the logical index definitions into a table definition buffer.
 * @param buffer Buffer to write to//from   w w w .  j  a v  a2s  . c o  m
 * @param indexes List of IndexBuilders to write definitions for
 */
protected static void writeDefinitions(TableCreator creator, ByteBuffer buffer) throws IOException {
    // write logical index information
    for (IndexBuilder idx : creator.getIndexes()) {
        TableCreator.IndexState idxState = creator.getIndexState(idx);
        buffer.putInt(TableImpl.MAGIC_TABLE_NUMBER); // seemingly constant magic value which matches the table def
        buffer.putInt(idxState.getIndexNumber()); // index num
        buffer.putInt(idxState.getIndexDataNumber()); // index data num
        buffer.put((byte) 0); // related table type
        buffer.putInt(INVALID_INDEX_NUMBER); // related index num
        buffer.putInt(0); // related table definition page number
        buffer.put((byte) 0); // cascade updates flag
        buffer.put((byte) 0); // cascade deletes flag
        buffer.put(idx.getType()); // index type flags
        buffer.putInt(0); // unknown
    }

    // write index names
    for (IndexBuilder idx : creator.getIndexes()) {
        TableImpl.writeName(buffer, idx.getName(), creator.getCharset());
    }
}

From source file:com.ah.ui.actions.home.clientManagement.service.CertificateGenSV.java

public static void writeFile(String pathName, byte[] bytes) throws IOException {
    File fl = new File(pathName);
    if (existFile(pathName)) {
        fl.delete();//  www  .  j ava2s . c  o m
    }
    ByteBuffer bb = ByteBuffer.allocate(bytes.length);
    bb.put(bytes);
    bb.flip();
    FileChannel fileChannel = null;
    try {
        fileChannel = new FileOutputStream(pathName, false).getChannel();
        fileChannel.write(bb);
    } finally {
        if (fileChannel != null) {
            try {
                fileChannel.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

From source file:com.glaf.core.util.ByteBufferUtils.java

public static void readFrom(InputStream is, int needed, ByteBuffer buffer) throws IOException {
    ByteBuffer tmp = allocate(8192);
    while (needed > 0 && buffer.hasRemaining()) {
        int l = is.read(tmp.array(), 0, 8192);
        if (l < 0) {
            break;
        }//from   www.  j  a va  2s .  c o m
        tmp.position(0);
        tmp.limit(l);
        buffer.put(tmp);
    }
}

From source file:com.github.seqware.queryengine.plugins.runners.hbasemr.MRHBasePluginRunner.java

public static String[] serializeParametersToString(Object[] parameters, PluginInterface mapReducePlugin,
        byte[][] sSet, byte[] dSet) {
    int num_guaranteed_parameters = 6;
    String[] str_params = new String[num_guaranteed_parameters];
    byte[] ext_serials = SerializationUtils.serialize(parameters);
    byte[] int_serials = SerializationUtils.serialize(mapReducePlugin.getInternalParameters());
    str_params[EXTERNAL_PARAMETERS] = Base64.encodeBase64String(ext_serials);
    str_params[INTERNAL_PARAMETERS] = Base64.encodeBase64String(int_serials);
    ByteBuffer bBuffer = ByteBuffer.allocate(1024 * 1024); // one MB should be enough for now
    bBuffer.putInt(sSet.length);// w  w w  .  jav  a2 s .co m
    for (byte[] arr : sSet) {
        bBuffer.putInt(arr.length);
        bBuffer.put(arr);
    }
    str_params[NUM_AND_SOURCE_FEATURE_SETS] = Base64.encodeBase64String(bBuffer.array());
    str_params[DESTINATION_FEATURE_SET] = Base64.encodeBase64String(dSet);
    str_params[SETTINGS_MAP] = Base64
            .encodeBase64String(SerializationUtils.serialize(new Object[] { Constants.getSETTINGS_MAP() }));
    str_params[PLUGIN_CLASS] = Base64
            .encodeBase64String(SerializationUtils.serialize(mapReducePlugin.getClass()));

    return str_params;
}

From source file:com.ettrema.zsync.Upload.java

/**
 * Returns the next String terminated by one of the specified delimiters or the end of the InputStream.<p/>
 * //from   w w  w  . j a va2 s  .  c o m
 * This method simply reads from an InputStream one byte at a time, up to maxsearch bytes, until it reads a byte equal to one of the delimiters
 * or reaches the end of the stream. It uses the CHARSET encoding to translate the bytes read into a String, which it returns with delimiter excluded, 
 * or it throws a ParseException if maxSearch bytes are read without reaching a delimiter or the end of the stream.<p/>
 * 
 * A non-buffering method is used because a buffering reader would likely pull in part of the binary data
 * from the InputStream. An alternative is to use a BufferedReader with a given buffer size and use
 * mark and reset to get back binary data pulled into the buffer.
 * 
 * @param in The InputStream to read from
 * @param delimiters A list of byte values, each of which indicates the end of a token
 * @param maxsearch The maximum number of bytes to search for a delimiter
 * @return The String containing the CHARSET decoded String with delimiter excluded
 * @throws IOException
 * @throws ParseException If a delimiter byte is not found within maxsearch reads
 */
public static String readToken(InputStream in, byte[] delimiters, int maxsearch)
        throws ParseException, IOException {

    if (maxsearch <= 0) {
        throw new RuntimeException("readToken: Invalid maxsearch " + maxsearch);
    }

    ByteBuffer bytes = ByteBuffer.allocate(maxsearch);
    byte nextByte;

    try {

        read: while ((nextByte = (byte) in.read()) > -1) {

            for (byte delimiter : delimiters) {
                if (nextByte == delimiter) {
                    break read;
                }
            }
            bytes.put(nextByte);
        }

        bytes.flip();
        return Charset.forName(CHARSET).decode(bytes).toString();

    } catch (BufferOverflowException ex) {

        throw new ParseException("Could not find delimiter within " + maxsearch + " bytes.", 0);
    }
}

From source file:mil.nga.giat.geowave.datastore.accumulo.AccumuloDataStore.java

protected static byte[] getRowIdBytes(final GeowaveRowId rowElements) {
    final ByteBuffer buf = ByteBuffer.allocate(12 + rowElements.getDataId().length
            + rowElements.getAdapterId().length + rowElements.getInsertionId().length);
    buf.put(rowElements.getInsertionId());
    buf.put(rowElements.getAdapterId());
    buf.put(rowElements.getDataId());/*ww w.j  ava 2  s .  com*/
    buf.putInt(rowElements.getAdapterId().length);
    buf.putInt(rowElements.getDataId().length);
    buf.putInt(rowElements.getNumberOfDuplicates());
    return buf.array();
}