Example usage for java.nio CharBuffer remaining

List of usage examples for java.nio CharBuffer remaining

Introduction

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

Prototype

public final int remaining() 

Source Link

Document

Returns the number of remaining elements in this buffer, that is limit - position .

Usage

From source file:BufferConverter.java

public static void main(String[] arguments) {
    try {//from w  ww. java 2s. com
        String data = "friends.dat";
        FileInputStream inData = new FileInputStream(data);
        FileChannel inChannel = inData.getChannel();
        long inSize = inChannel.size();
        ByteBuffer source = ByteBuffer.allocate((int) inSize);
        inChannel.read(source, 0);
        source.position(0);
        for (int i = 0; source.remaining() > 0; i++)
            System.out.print(source.get() + " ");

        source.position(0);
        Charset ascii = Charset.forName("US-ASCII");
        CharsetDecoder toAscii = ascii.newDecoder();
        CharBuffer destination = toAscii.decode(source);
        destination.position(0);
        System.out.println("\n\nNew character data:");
        for (int i = 0; destination.remaining() > 0; i++)
            System.out.print(destination.get());
    } catch (Exception ioe) {
        System.out.println(ioe.getMessage());
    }
}

From source file:Main.java

/**
 * Converts a byte array into a character array using the default character
 * set.//  w w w  .j  a  va2s.c o  m
 * 
 * @param bytes
 *            The source bytes.
 * @param charsetName
 *            The character set to use.
 * @return The result characters.
 */
public static char[] toCharArray(byte[] bytes, String charsetName) {
    java.nio.ByteBuffer bb = java.nio.ByteBuffer.wrap(bytes);
    java.nio.CharBuffer cb = java.nio.charset.Charset.forName(charsetName).decode(bb);
    char[] r = new char[cb.remaining()];
    cb.get(r);
    return r;
}

From source file:Main.java

private static ByteBuffer encode(CharBuffer in, CharsetEncoder encoder) {
    int length = (int) (in.remaining() * (double) encoder.averageBytesPerChar());
    ByteBuffer out = ByteBuffer.allocate(length);

    encoder.reset();//  w ww.j  a  v  a 2  s.c  o m
    CoderResult flushResult = null;

    while (flushResult != CoderResult.UNDERFLOW) {
        CoderResult encodeResult = encoder.encode(in, out, true);
        if (encodeResult == CoderResult.OVERFLOW) {
            out = allocateMore(out);
            continue;
        }

        flushResult = encoder.flush(out);
        if (flushResult == CoderResult.OVERFLOW) {
            out = allocateMore(out);
        }
    }

    out.flip();
    return out;
}

From source file:Main.java

/**
 * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true.
 *
 * @param content     the portion to decode
 * @param charset     the charset to use
 * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is.
 * @return encoded string/*w  w w .  j av  a2s  .c  om*/
 */
private static String urldecode(final String content, final Charset charset, final boolean plusAsBlank) {
    if (content == null) {
        return null;
    }
    ByteBuffer bb = ByteBuffer.allocate(content.length());
    CharBuffer cb = CharBuffer.wrap(content);
    while (cb.hasRemaining()) {
        char c = cb.get();
        if (c == '%' && cb.remaining() >= 2) {
            char uc = cb.get();
            char lc = cb.get();
            int u = Character.digit(uc, 16);
            int l = Character.digit(lc, 16);
            if (u != -1 && l != -1) {
                bb.put((byte) ((u << 4) + l));
            } else {
                bb.put((byte) '%');
                bb.put((byte) uc);
                bb.put((byte) lc);
            }
        } else if (plusAsBlank && c == '+') {
            bb.put((byte) ' ');
        } else {
            bb.put((byte) c);
        }
    }
    bb.flip();
    return charset.decode(bb).toString();
}

From source file:com.gistlabs.mechanize.util.apache.URLEncodedUtils.java

/**
 * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true.
 * //from  w  w w  .jav  a 2  s  .c  o  m
 * @param content the portion to decode
 * @param charset the charset to use
 * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is.
 * @return
 */
private static String urldecode(final String content, final Charset charset, final boolean plusAsBlank) {
    if (content == null)
        return null;
    ByteBuffer bb = ByteBuffer.allocate(content.length());
    CharBuffer cb = CharBuffer.wrap(content);
    while (cb.hasRemaining()) {
        char c = cb.get();
        if (c == '%' && cb.remaining() >= 2) {
            char uc = cb.get();
            char lc = cb.get();
            int u = Character.digit(uc, 16);
            int l = Character.digit(lc, 16);
            if (u != -1 && l != -1)
                bb.put((byte) ((u << 4) + l));
            else {
                bb.put((byte) '%');
                bb.put((byte) uc);
                bb.put((byte) lc);
            }
        } else if (plusAsBlank && c == '+')
            bb.put((byte) ' ');
        else
            bb.put((byte) c);
    }
    bb.flip();
    return charset.decode(bb).toString();
}

From source file:ChannelToWriter.java

/**
 * Read bytes from the specified channel, decode them using the specified
 * Charset, and write the resulting characters to the specified writer
 *//*from   w ww  . j a va2  s  .  c om*/
public static void copy(ReadableByteChannel channel, Writer writer, Charset charset) throws IOException {
    // Get and configure the CharsetDecoder we'll use
    CharsetDecoder decoder = charset.newDecoder();
    decoder.onMalformedInput(CodingErrorAction.IGNORE);
    decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);

    // Get the buffers we'll use, and the backing array for the CharBuffer.
    ByteBuffer bytes = ByteBuffer.allocateDirect(2 * 1024);
    CharBuffer chars = CharBuffer.allocate(2 * 1024);
    char[] array = chars.array();

    while (channel.read(bytes) != -1) { // Read from channel until EOF
        bytes.flip(); // Switch to drain mode for decoding
        // Decode the byte buffer into the char buffer.
        // Pass false to indicate that we're not done.
        decoder.decode(bytes, chars, false);

        // Put the char buffer into drain mode, and write its contents
        // to the Writer, reading them from the backing array.
        chars.flip();
        writer.write(array, chars.position(), chars.remaining());

        // Discard all bytes we decoded, and put the byte buffer back into
        // fill mode. Since all characters were output, clear that buffer.
        bytes.compact(); // Discard decoded bytes
        chars.clear(); // Clear the character buffer
    }

    // At this point there may still be some bytes in the buffer to decode
    // So put the buffer into drain mode call decode() a final time, and
    // finish with a flush().
    bytes.flip();
    decoder.decode(bytes, chars, true); // True means final call
    decoder.flush(chars); // Flush any buffered chars
    // Write these final chars (if any) to the writer.
    chars.flip();
    writer.write(array, chars.position(), chars.remaining());
    writer.flush();
}

From source file:com.mcxiaoke.next.http.util.URLUtils.java

/**
 * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true.
 *
 * @param content     the portion to decode
 * @param charset     the charset to use
 * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is.
 * @return encoded string//from   w  ww.  ja  va 2 s  . c  om
 */
private static String urlDecode(final String content, final Charset charset, final boolean plusAsBlank) {
    if (content == null) {
        return null;
    }
    final ByteBuffer bb = ByteBuffer.allocate(content.length());
    final CharBuffer cb = CharBuffer.wrap(content);
    while (cb.hasRemaining()) {
        final char c = cb.get();
        if (c == '%' && cb.remaining() >= 2) {
            final char uc = cb.get();
            final char lc = cb.get();
            final int u = Character.digit(uc, 16);
            final int l = Character.digit(lc, 16);
            if (u != -1 && l != -1) {
                bb.put((byte) ((u << 4) + l));
            } else {
                bb.put((byte) '%');
                bb.put((byte) uc);
                bb.put((byte) lc);
            }
        } else if (plusAsBlank && c == '+') {
            bb.put((byte) ' ');
        } else {
            bb.put((byte) c);
        }
    }
    bb.flip();
    return charset.decode(bb).toString();
}

From source file:Base64Encoder.java

/**
 * Encodes one or more characters into one or more bytes.
 *
 * <p> This method encapsulates the basic encoding loop, encoding as many
 * characters as possible until it either runs out of input, runs out of room
 * in the output buffer, or encounters an encoding error.  This method is
 * invoked by the {@link #encode encode} method, which handles result
 * interpretation and error recovery./*from   ww  w  . jav  a  2s  .c om*/
 *
 * <p> The buffers are read from, and written to, starting at their current
 * positions.  At most {@link Buffer#remaining in.remaining()} characters
 * will be read, and at most {@link Buffer#remaining out.remaining()}
 * bytes will be written.  The buffers' positions will be advanced to
 * reflect the characters read and the bytes written, but their marks and
 * limits will not be modified.
 *
 * <p> This method returns a {@link CoderResult} object to describe its
 * reason for termination, in the same manner as the {@link #encode encode}
 * method.  Most implementations of this method will handle encoding errors
 * by returning an appropriate result object for interpretation by the
 * {@link #encode encode} method.  An optimized implementation may instead
 * examine the relevant error action and implement that action itself.
 *
 * <p> An implementation of this method may perform arbitrary lookahead by
 * returning {@link CoderResult#UNDERFLOW} until it receives sufficient
 * input.  </p>
 *
 * @param  in
 *         The input character buffer
 *
 * @param  out
 *         The output byte buffer
 *
 * @return  A coder-result object describing the reason for termination
 */
public java.nio.charset.CoderResult encodeLoop(java.nio.CharBuffer in, java.nio.ByteBuffer out) {
    if (excessByte != null) {
        if (out.remaining() > 0) {
            out.put(excessByte.byteValue());
            excessByte = null;
        } else
            return CoderResult.OVERFLOW;

    }
    while (in.remaining() > 0) {
        char inch = in.get();
        int code = (int) inch >= encTable.length ? CHARCODE_INVALID : encTable[(int) inch];
        if (encState < 4) {
            switch (code) {
            case CHARCODE_INVALID:
                throw new IllegalArgumentException("Invalid base-64 character'" + inch + "'");
            case CHARCODE_WHITESPACE:
                break;
            case CHARCODE_PADDER:
                if (encState == 1)
                    throw new IllegalArgumentException("Mal-formed base-64 (= after one character");
                encState = 4;
                break;
            default:
                switch (encState) {
                case 0:
                    bits = code << 2;
                    encState = 1;
                    break;
                case 1:
                    encState = 2;
                    int v = bits | ((code >> 4) & 3);
                    bits = (code << 4) & 0xF0;
                    if (!out(out, v))
                        return CoderResult.OVERFLOW;
                    break;
                case 2:
                    encState = 3;
                    v = bits | (code >> 2) & 0x0f;
                    bits = (code << 6) & 0xC0;
                    if (!out(out, v))
                        return CoderResult.OVERFLOW;
                    break;
                case 3:
                    encState = 0;
                    bits |= (code & 0x3f);
                    if (!out(out, bits))
                        return CoderResult.OVERFLOW;
                    break;
                }

                break;
            }

        }
    }
    return CoderResult.UNDERFLOW;
}

From source file:de.undercouch.bson4jackson.BsonGeneratorTest.java

private void assertRaw(byte[] r) throws Exception {
    ByteArrayInputStream bais = new ByteArrayInputStream(r);
    BSONDecoder decoder = new BasicBSONDecoder();
    BSONObject obj = decoder.readObject(bais);
    byte[] o = (byte[]) obj.get("Test");
    CharBuffer buf = ByteBuffer.wrap(o).order(ByteOrder.LITTLE_ENDIAN).asCharBuffer();
    assertEquals(2, buf.remaining());
    char a = buf.get();
    char b = buf.get();
    assertEquals('a', a);
    assertEquals('b', b);
}

From source file:com.asakusafw.runtime.io.csv.CsvParser.java

private int getNextCharacter() throws IOException {
    CharBuffer buf = readerBuffer;
    if (buf.remaining() == 0) {
        buf.clear();//w w w .j  a v a 2 s .  c o m
        int read = reader.read(buf);
        buf.flip();
        assert read != 0;
        if (read < 0) {
            return EOF;
        }
    }
    return buf.get();
}