Example usage for java.nio CharBuffer capacity

List of usage examples for java.nio CharBuffer capacity

Introduction

In this page you can find the example usage for java.nio CharBuffer capacity.

Prototype

public final int capacity() 

Source Link

Document

Returns the capacity of this buffer.

Usage

From source file:MainClass.java

public static void main(String argv[]) {
    ByteBuffer bb = ByteBuffer.allocate(100);

    bb.mark();/*from  w ww.  ja v a 2  s .c o m*/
    bb.position(5);
    bb.reset();

    bb.mark().position(5).reset();

    char[] myBuffer = new char[100];

    CharBuffer cb = CharBuffer.wrap(myBuffer);
    cb.position(12).limit(21);

    CharBuffer sliced = cb.slice();

    System.out.println("Sliced: offset=" + sliced.arrayOffset() + ", capacity=" + sliced.capacity());
}

From source file:MainClass.java

public static void main(String[] args) {
    String[] phrases = { "A", "B 1", "C 1.3" };
    String dirname = "C:/test";
    String filename = "Phrases.txt";
    File dir = new File(dirname);
    File aFile = new File(dir, filename);
    FileOutputStream outputFile = null;
    try {/*from  ww  w .  jav a 2  s .  c om*/
        outputFile = new FileOutputStream(aFile, true);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    FileChannel outChannel = outputFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println(buf.position());
    System.out.println(buf.limit());
    System.out.println(buf.capacity());
    CharBuffer charBuf = buf.asCharBuffer();
    System.out.println(charBuf.position());
    System.out.println(charBuf.limit());
    System.out.println(charBuf.capacity());
    Formatter formatter = new Formatter(charBuf);
    int number = 0;
    for (String phrase : phrases) {
        formatter.format("%n %s", ++number, phrase);
        System.out.println(charBuf.position());
        System.out.println(charBuf.limit());
        System.out.println(charBuf.capacity());
        charBuf.flip();
        System.out.println(charBuf.position());
        System.out.println(charBuf.limit());
        System.out.println(charBuf.length());
        buf.limit(2 * charBuf.length()); // Set byte buffer limit
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.remaining());
        try {
            outChannel.write(buf);
            buf.clear();
            charBuf.clear();
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    }
    try {
        outputFile.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    File aFile = new File("afile.txt");
    FileOutputStream outputFile = null;
    try {/*from w  ww .j av a2  s . c  o m*/
        outputFile = new FileOutputStream(aFile, true);
        System.out.println("File stream created successfully.");
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println("\nByte buffer:");
    System.out.printf("position = %2d  Limit = %4d  capacity = %4d%n", buf.position(), buf.limit(),
            buf.capacity());

    // Create a view buffer
    CharBuffer charBuf = buf.asCharBuffer();
    System.out.println("Char view buffer:");
    System.out.printf("position = %2d  Limit = %4d  capacity = %4d%n", charBuf.position(), charBuf.limit(),
            charBuf.capacity());
    try {
        outputFile.close(); // Close the O/P stream & the channel
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:MainClass.java

private static void println(CharBuffer cb) {
    System.out.println("pos=" + cb.position() + ", limit=" + cb.limit() + ", capacity=" + cb.capacity() + ": '"
            + cb + "'");
}

From source file:MainClass.java

private static void println(CharBuffer cb) {
    System.out.println("pos=" + cb.position() + ", limit=" + cb.limit() + ", capacity=" + cb.capacity()
            + ", arrayOffset=" + cb.arrayOffset());
}

From source file:com.gamesalutes.utils.ByteUtils.java

/**
 * Extends the size of <code>buf</code> to at least meet <code>minCap</code>.
 * If <code>buf</code> is too small, then a new buffer is allocated and
 * any existing contents in <code>buf</code> will be transfered.  The position
 * of the new buffer will be that of the old buffer if it was not <code>null</code>, and
 * the previous mark will be discarded if one was set.
 * //  ww w . j a  v a2 s  . c  om
 * @param buf the input <code>ByteBuffer</code>
 * @param minCap the minimum capacity
 * @return a <code>CharBuffer</code> that can meet <code>minCap</code>
 */
public static CharBuffer growBuffer(CharBuffer buf, int minCap) {
    int myLimit = buf != null ? buf.limit() : 0;
    // limit can accomidate capacity requirements
    if (buf != null && myLimit >= minCap)
        return buf;
    int myCap = buf != null ? buf.capacity() : 0;
    // capacity can accomidate but limit is too small
    if (buf != null && myCap >= minCap) {
        buf.limit(myCap);
        return buf;
    } else //if(myCap < minCap)
    {
        CharBuffer newBuffer = null;
        if (myCap == 0)
            myCap = 1;
        while (myCap < minCap)
            myCap <<= 1;
        //         if(buf != null && buf.isDirect())
        //            newBuffer = CharBuffer.allocateDirect(myCap);
        //         else
        newBuffer = CharBuffer.allocate(myCap);
        // copy contents of original buffer
        if (buf != null) {
            int pos = buf.position();
            buf.clear();
            newBuffer.put(buf);
            newBuffer.position(pos);
        }
        return newBuffer;

    }
}

From source file:de.undercouch.bson4jackson.io.StaticBuffers.java

/**
 * Creates or re-uses a {@link CharBuffer} that has a minimum size. Calling
 * this method multiple times with the same key will always return the
 * same buffer, as long as it has the minimum size and is marked to be
 * re-used. Buffers that are allowed to be re-used should be released using
 * {@link #releaseCharBuffer(Key, CharBuffer)}.
 * @param key the buffer's identifier//from   w  w  w .j av a 2  s.  c  om
 * @param minSize the minimum size
 * @return the {@link CharBuffer} instance
 */
public CharBuffer charBuffer(Key key, int minSize) {
    minSize = Math.max(minSize, GLOBAL_MIN_SIZE);

    CharBuffer r = _charBuffers[key.ordinal()];
    if (r == null || r.capacity() < minSize) {
        r = CharBuffer.allocate(minSize);
    } else {
        _charBuffers[key.ordinal()] = null;
        r.clear();
    }
    return r;
}

From source file:com.cloudbees.jenkins.support.filter.FilteredWriterTest.java

@Issue("JENKINS-21670")
@Test/*www .  j  a  v a 2 s .  c o m*/
public void shouldSupportLinesLongerThanDefaultBufferSize() throws Exception {
    CharBuffer input = CharBuffer.allocate(FilteredConstants.DEFAULT_DECODER_CAPACITY * 10);
    for (int i = 0; i < input.capacity(); i++) {
        input.put('+');
    }
    input.flip();
    CharSequenceReader reader = new CharSequenceReader(input);
    ContentFilter filter = s -> s.replace('+', '-');
    StringWriter output = new StringWriter();
    FilteredWriter writer = new FilteredWriter(output, filter);

    IOUtils.copy(reader, writer);
    assertThat(output.toString()).isEmpty();

    writer.flush();

    assertThat(output.toString()).isNotEmpty().matches("^-+$");

}

From source file:com.cloudbees.jenkins.support.filter.FilteredOutputStreamTest.java

@Issue("JENKINS-21670")
@Test// www .  j a  v a  2 s. com
public void shouldSupportLinesLargerThanDefaultBufferSize() throws IOException {
    CharBuffer input = CharBuffer.allocate(FilteredConstants.DEFAULT_DECODER_CAPACITY * 10);
    for (int i = 0; i < input.capacity(); i++) {
        input.put('*');
    }
    input.flip();
    InputStream in = new CharSequenceInputStream(input, UTF_8);
    FilteredOutputStream out = new FilteredOutputStream(testOutput, s -> s.replace('*', 'a'));

    IOUtils.copy(in, out);
    String contents = new String(testOutput.toByteArray(), UTF_8);

    assertThat(contents).isEmpty();

    out.flush();
    contents = new String(testOutput.toByteArray(), UTF_8);

    assertThat(contents).isNotEmpty().matches("^a+$");
}

From source file:com.google.flatbuffers.Table.java

/**
 * Create a Java `String` from UTF-8 data stored inside the FlatBuffer.
 *
 * This allocates a new string and converts to wide chars upon each access,
 * which is not very efficient. Instead, each FlatBuffer string also comes with an
 * accessor based on __vector_as_bytebuffer below, which is much more efficient,
 * assuming your Java program can handle UTF-8 data directly.
 *
 * @param offset An `int` index into the Table's ByteBuffer.
 * @return Returns a `String` from the data stored inside the FlatBuffer at `offset`.
 *//*  www  .ja  va  2s .  c  o  m*/
protected String __string(int offset) {
    CharsetDecoder decoder = UTF8_DECODER.get();
    decoder.reset();

    offset += bb.getInt(offset);
    ByteBuffer src = bb.duplicate().order(ByteOrder.LITTLE_ENDIAN);
    int length = src.getInt(offset);
    src.position(offset + SIZEOF_INT);
    src.limit(offset + SIZEOF_INT + length);

    int required = (int) ((float) length * decoder.maxCharsPerByte());
    CharBuffer dst = CHAR_BUFFER.get();
    if (dst == null || dst.capacity() < required) {
        dst = CharBuffer.allocate(required);
        CHAR_BUFFER.set(dst);
    }

    dst.clear();

    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new Error(x);
    }

    return dst.flip().toString();
}