Пример #1
0
 public static void main(String[] args) {
   ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 'a'});
   bb.rewind();
   printnb("Byte Buffer ");
   while (bb.hasRemaining()) printnb(bb.position() + " -> " + bb.get() + ", ");
   print();
   CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer();
   printnb("Char Buffer ");
   while (cb.hasRemaining()) printnb(cb.position() + " -> " + cb.get() + ", ");
   print();
   FloatBuffer fb = ((ByteBuffer) bb.rewind()).asFloatBuffer();
   printnb("Float Buffer ");
   while (fb.hasRemaining()) printnb(fb.position() + " -> " + fb.get() + ", ");
   print();
   IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer();
   printnb("Int Buffer ");
   while (ib.hasRemaining()) printnb(ib.position() + " -> " + ib.get() + ", ");
   print();
   LongBuffer lb = ((ByteBuffer) bb.rewind()).asLongBuffer();
   printnb("Long Buffer ");
   while (lb.hasRemaining()) printnb(lb.position() + " -> " + lb.get() + ", ");
   print();
   ShortBuffer sb = ((ByteBuffer) bb.rewind()).asShortBuffer();
   printnb("Short Buffer ");
   while (sb.hasRemaining()) printnb(sb.position() + " -> " + sb.get() + ", ");
   print();
   DoubleBuffer db = ((ByteBuffer) bb.rewind()).asDoubleBuffer();
   printnb("Double Buffer ");
   while (db.hasRemaining()) printnb(db.position() + " -> " + db.get() + ", ");
 }
Пример #2
0
  protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) {
    int mark = src.position();

    if (needsMark) {
      if (dst.remaining() < 2) return CoderResult.OVERFLOW;
      put(BYTE_ORDER_MARK, dst);
      needsMark = false;
    }

    try {
      while (src.hasRemaining()) {
        char c = src.get();
        if (!Surrogate.is(c)) {
          if (dst.remaining() < 2) return CoderResult.OVERFLOW;
          mark++;
          put(c, dst);
          continue;
        }
        int d = sgp.parse(c, src);
        if (d < 0) return sgp.error();
        if (dst.remaining() < 4) return CoderResult.OVERFLOW;
        mark += 2;
        put(Surrogate.high(d), dst);
        put(Surrogate.low(d), dst);
      }
      return CoderResult.UNDERFLOW;
    } finally {
      src.position(mark);
    }
  }
Пример #3
0
 public static void main(String[] arguments) {
   try {
     // read byte data into a byte buffer
     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);
     System.out.println("Original byte data:");
     for (int i = 0; source.remaining() > 0; i++) {
       System.out.print(source.get() + " ");
     }
     // convert byte data into character data
     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());
     }
     System.out.println();
   } catch (FileNotFoundException fne) {
     System.out.println(fne.getMessage());
   } catch (IOException ioe) {
     System.out.println(ioe.getMessage());
   }
 }
Пример #4
0
  /**
   * Gets a Reader for a text flavor, decoded, if necessary, for the expected charset (encoding).
   * The supported representation classes are <code>java.io.Reader</code>, <code>java.lang.String
   * </code>, <code>java.nio.CharBuffer</code>, <code>[C</code>, <code>java.io.InputStream</code>,
   * <code>java.nio.ByteBuffer</code>, and <code>[B</code>.
   *
   * <p>Because text flavors which do not support the charset parameter are encoded in a
   * non-standard format, this method should not be called for such flavors. However, in order to
   * maintain backward-compatibility, if this method is called for such a flavor, this method will
   * treat the flavor as though it supports the charset parameter and attempt to decode it
   * accordingly. See <code>selectBestTextFlavor</code> for a list of text flavors which do not
   * support the charset parameter.
   *
   * @param transferable the <code>Transferable</code> whose data will be requested in this flavor
   * @return a <code>Reader</code> to read the <code>Transferable</code>'s data
   * @exception IllegalArgumentException if the representation class is not one of the seven listed
   *     above
   * @exception IllegalArgumentException if the <code>Transferable</code> has <code>null</code> data
   * @exception NullPointerException if the <code>Transferable</code> is <code>null</code>
   * @exception UnsupportedEncodingException if this flavor's representation is <code>
   *     java.io.InputStream</code>, <code>java.nio.ByteBuffer</code>, or <code>[B</code> and this
   *     flavor's encoding is not supported by this implementation of the Java platform
   * @exception UnsupportedFlavorException if the <code>Transferable</code> does not support this
   *     flavor
   * @exception IOException if the data cannot be read because of an I/O error
   * @see #selectBestTextFlavor
   * @since 1.3
   */
  public Reader getReaderForText(Transferable transferable)
      throws UnsupportedFlavorException, IOException {
    Object transferObject = transferable.getTransferData(this);
    if (transferObject == null) {
      throw new IllegalArgumentException("getTransferData() returned null");
    }

    if (transferObject instanceof Reader) {
      return (Reader) transferObject;
    } else if (transferObject instanceof String) {
      return new StringReader((String) transferObject);
    } else if (transferObject instanceof CharBuffer) {
      CharBuffer buffer = (CharBuffer) transferObject;
      int size = buffer.remaining();
      char[] chars = new char[size];
      buffer.get(chars, 0, size);
      return new CharArrayReader(chars);
    } else if (transferObject instanceof char[]) {
      return new CharArrayReader((char[]) transferObject);
    }

    InputStream stream = null;

    if (transferObject instanceof InputStream) {
      stream = (InputStream) transferObject;
    } else if (transferObject instanceof ByteBuffer) {
      ByteBuffer buffer = (ByteBuffer) transferObject;
      int size = buffer.remaining();
      byte[] bytes = new byte[size];
      buffer.get(bytes, 0, size);
      stream = new ByteArrayInputStream(bytes);
    } else if (transferObject instanceof byte[]) {
      stream = new ByteArrayInputStream((byte[]) transferObject);
    }

    if (stream == null) {
      throw new IllegalArgumentException(
          "transfer data is not Reader, String, CharBuffer, char array, InputStream, ByteBuffer, or byte array");
    }

    String encoding = getParameter("charset");
    return (encoding == null)
        ? new InputStreamReader(stream)
        : new InputStreamReader(stream, encoding);
  }
  public CharBuffer get(char[] dst, int offset, int length) {

    if ((length << 1) > Bits.JNI_COPY_TO_ARRAY_THRESHOLD) {
      checkBounds(offset, length, dst.length);
      int pos = position();
      int lim = limit();
      assert (pos <= lim);
      int rem = (pos <= lim ? lim - pos : 0);
      if (length > rem) throw new BufferUnderflowException();

      if (order() != ByteOrder.nativeOrder())
        Bits.copyToCharArray(ix(pos), dst, offset << 1, length << 1);
      else Bits.copyToByteArray(ix(pos), dst, offset << 1, length << 1);
      position(pos + length);
    } else {
      super.get(dst, offset, length);
    }
    return this;
  }
Пример #6
0
 static char[] decode(byte[] bb, Charset cs, boolean testDirect, Time t) throws Exception {
   String csn = cs.name();
   CharsetDecoder dec = cs.newDecoder();
   ByteBuffer bbf;
   CharBuffer cbf;
   if (testDirect) {
     bbf = ByteBuffer.allocateDirect(bb.length);
     cbf = ByteBuffer.allocateDirect(bb.length * 2).asCharBuffer();
     bbf.put(bb);
   } else {
     bbf = ByteBuffer.wrap(bb);
     cbf = CharBuffer.allocate(bb.length);
   }
   CoderResult cr = null;
   long t1 = System.nanoTime() / 1000;
   for (int i = 0; i < iteration; i++) {
     bbf.rewind();
     cbf.clear();
     dec.reset();
     cr = dec.decode(bbf, cbf, true);
   }
   long t2 = System.nanoTime() / 1000;
   t.t = (t2 - t1) / iteration;
   if (cr != CoderResult.UNDERFLOW) {
     System.out.println("DEC-----------------");
     int pos = bbf.position();
     System.out.printf(
         "  cr=%s, bbf.pos=%d, bb[pos]=%x,%x,%x,%x%n",
         cr.toString(),
         pos,
         bb[pos++] & 0xff,
         bb[pos++] & 0xff,
         bb[pos++] & 0xff,
         bb[pos++] & 0xff);
     throw new RuntimeException("Decoding err: " + csn);
   }
   char[] cc = new char[cbf.position()];
   cbf.flip();
   cbf.get(cc);
   return cc;
 }
Пример #7
0
 @Override
 int read(final TextInput ti) throws IOException {
   int c = -1;
   while (++c < 4) {
     final int ch = ti.readByte();
     if (ch < 0) break;
     cache[c] = (byte) ch;
     outc.position(0);
     inc.position(0);
     inc.limit(c + 1);
     csd.reset();
     final CoderResult cr = csd.decode(inc, outc, true);
     if (cr.isMalformed()) continue;
     // return character
     int i = 0;
     final int os = outc.position();
     for (int o = 0; o < os; ++o) i |= outc.get(o) << (o << 3);
     return i;
   }
   return c == 0 ? -1 : invalid();
 }
  public static void main(String[] args) throws Exception {
    System.out.println(">>> StringCharBufferSliceTest-main: testing the slice method...");

    final String in = "for testing";

    System.out.println(">>> StringCharBufferSliceTest-main: testing with the position 0.");

    CharBuffer buff = CharBuffer.wrap(in);
    test(buff, buff.slice());

    System.out.println(">>> StringCharBufferSliceTest-main: testing with new position.");

    buff.position(2);
    test(buff, buff.slice());

    System.out.println(
        ">>> StringCharBufferSliceTest-main: testing with non zero initial position.");

    buff = CharBuffer.wrap(in, 3, in.length());
    test(buff, buff.slice());

    System.out.println(">>> StringCharBufferSliceTest-main: testing slice result with get()");
    buff.position(4);
    buff.limit(7);
    CharBuffer slice = buff.slice();
    for (int i = 0; i < 3; i++) {
      if (slice.get() != buff.get()) {
        throw new RuntimeException("Wrong characters in slice result.");
      }
    }

    System.out.println(">>> StringCharBufferSliceTest-main: testing slice result with get(int)");
    buff.position(4);
    buff.limit(7);
    slice = buff.slice();
    for (int i = 0; i < 3; i++) {
      if (slice.get(i) != buff.get(4 + i)) {
        throw new RuntimeException("Wrong characters in slice result.");
      }
    }

    System.out.println(">>> StringCharBufferSliceTest-main: testing slice with result of slice");
    buff.position(0);
    buff.limit(buff.capacity());
    slice = buff.slice();
    for (int i = 0; i < 4; i++) {
      slice.position(i);
      CharBuffer nextSlice = slice.slice();
      if (nextSlice.position() != 0)
        throw new RuntimeException("New buffer's position should be zero");
      if (!nextSlice.equals(slice)) throw new RuntimeException("New buffer should be equal");
      slice = nextSlice;
    }

    System.out.println(">>> StringCharBufferSliceTest-main: testing toString.");
    buff.position(4);
    buff.limit(7);
    slice = buff.slice();
    if (!slice.toString().equals("tes")) {
      throw new RuntimeException("bad toString() after slice(): " + slice.toString());
    }

    System.out.println(">>> StringCharBufferSliceTest-main: testing subSequence.");
    buff.position(4);
    buff.limit(8);
    slice = buff.slice();
    CharSequence subSeq = slice.subSequence(1, 3);
    if (subSeq.charAt(0) != 'e' || subSeq.charAt(1) != 's') {
      throw new RuntimeException("bad subSequence() after slice(): '" + subSeq + "'");
    }

    System.out.println(">>> StringCharBufferSliceTest-main: testing duplicate.");
    buff.position(4);
    buff.limit(8);
    slice = buff.slice();
    CharBuffer dupe = slice.duplicate();
    if (dupe.charAt(0) != 't'
        || dupe.charAt(1) != 'e'
        || dupe.charAt(2) != 's'
        || dupe.charAt(3) != 't') {
      throw new RuntimeException("bad duplicate() after slice(): '" + dupe + "'");
    }

    System.out.println(">>> StringCharBufferSliceTest-main: done!");
  }