示例#1
0
  public static void writeChannel() {
    FileOutputStream fileOut = null;
    FileChannel channel = null;
    try {
      InputStream input = FileChannelIoMain.class.getClassLoader().getResourceAsStream("test.txt");
      byte[] byteBuffer = new byte[1024];

      int size = 0;
      StringBuilder builer = new StringBuilder();
      while ((size = input.read(byteBuffer)) != -1) {
        builer.append(new String(byteBuffer));
      }
      System.out.println(builer.toString());

      File file = new File("./test.txt");
      if (!file.exists()) {
        file.createNewFile();
        file.setWritable(true);
      }
      fileOut = new FileOutputStream(file, true);
      channel = fileOut.getChannel();

      ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
      buffer.putChar('\n');

      buffer.put("我是一个中国人,我的家乡在北京".getBytes("utf-8"));

      buffer.mark();

      buffer.putChar('&');
      buffer.putChar('#');

      buffer.reset();
      buffer.flip();

      // buffer.rewind();

      channel.write(buffer);

      buffer.clear();

    } catch (Throwable e) {
      e.printStackTrace();
    } finally {
      try {
        if (fileOut != null) {
          fileOut.close();
          fileOut = null;
        }
        if (channel != null) {
          channel.close();
          channel = null;
        }
      } catch (Throwable e) {
        e.printStackTrace();
      }
    }
  }
示例#2
0
 /**
  * Write String to buffer
  *
  * @param buf
  * @param text
  */
 protected final void writeS(String text) {
   if (text == null) {
     buf.putChar('\000');
   } else {
     final int len = text.length();
     for (int i = 0; i < len; i++) buf.putChar(text.charAt(i));
     buf.putChar('\000');
   }
 }
示例#3
0
  /** @see MemoryUtil#memUTF16(CharSequence, boolean, ByteBuffer, int) */
  int encodeUTF16(CharSequence text, boolean nullTerminated, ByteBuffer target, int offset) {
    int p = offset;
    for (int i = 0; i < text.length(); i++, p += 2) target.putChar(p, text.charAt(i));

    if (nullTerminated) {
      target.putChar(p, '\0');
      p += 2;
    }

    return p - offset;
  }
示例#4
0
    public boolean serialize(ByteBuffer buffer) {
      try {
        buffer.put(unknown8);
        buffer.put(unknown9);
        buffer.put(unknown10);
        buffer.put(unknown11);
        buffer.put(unknown12);
        buffer.put(unknown13);
        buffer.put(unknown14);
        buffer.putShort(unknown15);
        buffer.put(unknown16);
        short prefix_unknown17;
        if (unknown17 == null) {
          prefix_unknown17 = 0;
        } else {
          prefix_unknown17 = (short) unknown17.length;
        }
        buffer.putShort(prefix_unknown17);

        for (int i = 0; i < prefix_unknown17; i++) {
          buffer.putChar(unknown17[i]);
        }
      } catch (BufferOverflowException e) {
        return false;
      }

      return true;
    }
  @Override
  public byte[] getBytes() {
    ByteBuffer byteBuffer = ByteBuffer.allocate(98);
    byteBuffer.order(ByteOrder.BIG_ENDIAN);

    byteBuffer.putLong(0, this.getConnectionId());
    byteBuffer.putInt(8, this.getAction().value());
    byteBuffer.putInt(12, this.getTransactionId());
    byteBuffer.position(16);
    byteBuffer.put(infoHash.getBytes());
    byteBuffer.position(36);
    byteBuffer.put(peerId.getBytes());
    byteBuffer.putLong(56, downloaded);
    byteBuffer.putLong(64, left);
    byteBuffer.putLong(72, uploaded);
    byteBuffer.putInt(80, this.getEvent().value());
    byteBuffer.putInt(84, peerInfo.getIpAddress());
    byteBuffer.putInt(88, key);
    byteBuffer.putInt(92, numWant);
    byteBuffer.putChar(96, (char) peerInfo.getPort());

    byteBuffer.flip();

    return byteBuffer.array();
  }
示例#6
0
  @Override
  public boolean serialize() {
    int size = getSize();

    if (size == 0) {
      return false;
    }

    ByteBuffer buffer = ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN);

    try {
      buffer.putShort(getHeader());

      short prefix_unknown1;
      if (unknown1 == null) {
        prefix_unknown1 = 0;
      } else {
        prefix_unknown1 = (short) unknown1.length;
      }
      buffer.putShort(prefix_unknown1);

      for (int i = 0; i < prefix_unknown1; i++) {
        buffer.putChar(unknown1[i]);
      }
    } catch (BufferOverflowException e) {
      return false;
    }

    setBuffer(buffer);

    return true;
  }
示例#7
0
  public void save(int pageNo, B_Tree.Page<Key> page) {
    try {
      ByteBuffer buffer = ByteBuffer.allocate(pageSize);
      List<B_Tree.KeyPointer<Key>> ptrs = page.keyPointers;
      boolean isBranch = !ptrs.isEmpty() && ptrs.get(0).t2 instanceof B_Tree.Branch;

      buffer.putChar(isBranch ? INTERNAL : LEAF);
      buffer.putInt(ptrs.size());

      for (B_Tree.KeyPointer<Key> keyPtr : ptrs) {
        keyAccessor.write(buffer, keyPtr.t1);

        if (keyPtr.t2 instanceof B_Tree.Branch) {
          int branch = ((B_Tree.Branch) keyPtr.t2).branch;
          buffer.putInt(branch);
        } else if (keyPtr.t2 instanceof B_Tree.Leaf) {
          @SuppressWarnings("unchecked")
          Value value = ((B_Tree.Leaf<Value>) keyPtr.t2).value;
          valueAccessor.write(buffer, value);
        }
      }

      buffer.flip();
      channel.write(buffer, pageNo * pageSize);
    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }
  }
示例#8
0
 public LogBuffer put(char[] chars) throws IOException {
   ensureConversionBufferCapacity(chars.length * 2);
   bufferForConversions.clear();
   for (char ch : chars) {
     bufferForConversions.putChar(ch);
   }
   return flipAndPut();
 }
 public static void prepareBuffer(String massg) {
   try {
     WriteBuffer.clear();
     WriteBuffer.put(massg.getBytes("ISO-8859-1"));
     WriteBuffer.putChar('\n');
     WriteBuffer.flip();
   } catch (Exception e) {
   }
 }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!(obj instanceof Character)) {
     return super.write(buff, obj);
   }
   buff.put((byte) TYPE_CHAR);
   buff.putChar(((Character) obj).charValue());
   return buff;
 }
 /**
  * Send as many items as possible from this buffer to the given byte buffer.
  *
  * <p>The <TT>sendItems()</TT> method must not block the calling thread; if it does, all message
  * I/O in MP will be blocked.
  *
  * @param i Index of first item to send, in the range 0 .. <TT>length</TT>-1.
  * @param buffer Byte buffer.
  * @return Number of items sent.
  */
 protected int sendItems(int i, ByteBuffer buffer) {
   int index = i;
   int off = myArrayOffset + i;
   while (index < myLength && buffer.remaining() >= 2) {
     buffer.putChar(myArray.get(off));
     ++index;
     ++off;
   }
   return index - i;
 }
 @Override
 protected void toWireUnchecked(IpmiPacketContext context, ByteBuffer buffer) {
   buffer.put(messageTag);
   buffer.put(Bits.toByte(requestedMaximumPrivilegeLevel));
   buffer.putChar((char) 0); // reserved
   toWireIntLE(buffer, consoleSessionId);
   IpmiAlgorithmUtils.toWireUnchecked(buffer, authenticationAlgorithm);
   IpmiAlgorithmUtils.toWireUnchecked(buffer, integrityAlgorithm);
   IpmiAlgorithmUtils.toWireUnchecked(buffer, confidentialityAlgorithm);
 }
示例#13
0
  public ByteBuffer asByteBuffer() {
    if ((statusCode == StatusCode.NO_CLOSE)
        || (statusCode == StatusCode.NO_CODE)
        || (statusCode == (-1))) {
      // codes that are not allowed to be used in endpoint.
      return null;
    }

    ByteBuffer buf = ByteBuffer.allocate(WebSocketFrame.MAX_CONTROL_PAYLOAD);
    buf.putChar((char) statusCode);
    if (StringUtil.isNotBlank(reason)) {
      byte utf[] = StringUtil.getUtf8Bytes(reason);
      buf.put(utf, 0, utf.length);
    }
    BufferUtil.flipToFlush(buf, 0);
    return buf;
  }
  public boolean update() {
    Log.w(TAG, "Updating registry.");
    Network_Msg msg;
    ByteBuffer payload;

    lat = 39; // PoRegistryService.getInstance().getLat();
    lon = 22; // PoRegistryService.getInstance().getLon();

    byte payload_len = (byte) (1 + 8 + 8 + 2 + 4); // Class of device + Lat + long + addr + seed

    Log.e(TAG, "Current latitude: " + lat);
    Log.e(TAG, "Current longitude: " + lon);

    payload = ByteBuffer.allocate(Serialization.uint8ToInt(payload_len));
    payload.put(Network_Msg.CLASS_MOBILE).putDouble(lat).putDouble(lon);
    payload.putChar(addr).putInt(seed);
    payload.position(0);

    msg = new Network_Msg(Network_Msg.REGISTRY_REQ, payload_len, payload.array());
    payload.clear();
    return PoConnectionManager.getInstance().getOutMsgQ().offer(msg);
  }
示例#15
0
 public void putChars(char text[], int start, int len) {
   grow(len * Character.SIZE + Integer.SIZE);
   byteBuffer.putInt(len);
   for (int i = 0; i < len; i++) byteBuffer.putChar(text[start + i]);
 }
示例#16
0
 /**
  * Puts a character into the the buffer.
  *
  * @param c
  */
 public void putCharacter(char c) {
   verifySize(2);
   buf.putChar(c);
 }
示例#17
0
 /**
  * Append the given {@code char} to this {@literal Buffer}.
  *
  * @param c The {@code char} to append.
  * @return {@literal this}
  */
 public Buffer append(char c) {
   ensureCapacity(2);
   buffer.putChar(c);
   return this;
 }
 public void writeChar(char value) {
   ByteBuffer buffer = getBufferWithCapacity(2);
   buffer.putChar(value);
 }
示例#19
0
 /**
  * Puts a String into the the buffer.
  *
  * @param c
  */
 public void putString(String c) {
   verifySize(2 * c.length());
   for (int i = 0; i < c.length(); i++) {
     buf.putChar(c.charAt(i));
   }
 }
 /**
  * Adds a char to the data.
  *
  * @param value The char to add.
  */
 public void composeChar(char value) {
   dataBuffer.putChar(value);
 }
示例#21
0
 /* @see java.io.DataOutput.writeChar(int) */
 public void writeChar(int v) throws IOException {
   writeSetup(2);
   buffer.putChar((char) v);
   doWrite(2);
 }
示例#22
0
 /**
  * Writes an array of chars to the underlying stream. If the underlying stream does not contain
  * enough of free space to write it will be expanded before it is written to. A char takes up 2
  * bytes.
  *
  * @param x The array to write to the stream.
  */
 public void putChars(char[] x) {
   ByteBuffer b = stream.getWriter(x.length << 1);
   for (int i = 0; i < x.length; i++) {
     b.putChar(x[i]);
   }
 }
示例#23
0
 /* (non-Javadoc)
  * @see edu.tsinghua.lumaqq.qq.packets.OutPacket#putBody(java.nio.ByteBuffer)
  */
 @Override
 protected void putBody(ByteBuffer buf) {
   // 短消息序号
   buf.putChar(messageSequence);
   // 未知2字节
   buf.putChar((char) 0);
   // 未知4字节
   buf.putInt(0);
   // 发送者昵称
   byte[] b = Util.getBytes(senderName);
   if (b.length > QQ.QQ_MAX_SMS_SENDER_NAME) {
     buf.put(b, 0, QQ.QQ_MAX_SMS_SENDER_NAME);
   } else {
     buf.put(b);
     int stuff = QQ.QQ_MAX_SMS_SENDER_NAME - b.length;
     while (stuff-- > 0) buf.put((byte) 0);
   }
   // 未知1字节
   buf.put((byte) 0x01);
   // 发送模式
   buf.put(sendMode);
   // 内容类型
   buf.put(contentType);
   // 内容编号
   buf.putInt(contentId);
   // 未知1字节
   buf.put((byte) 0x01);
   // 手机个数
   if (receiverMobile == null) buf.put((byte) 0);
   else {
     buf.put((byte) receiverMobile.size());
     for (String mobile : receiverMobile) {
       b = Util.getBytes(mobile);
       if (b.length > QQ.QQ_MAX_SMS_MOBILE_LENGTH) {
         buf.put(b, 0, QQ.QQ_MAX_SMS_MOBILE_LENGTH);
       } else {
         buf.put(b);
         int stuff = QQ.QQ_MAX_SMS_MOBILE_LENGTH - b.length;
         while (stuff-- > 0) buf.put((byte) 0);
       }
       // 未知的2字节
       buf.putChar((char) 0);
       // 未知的1字节
       buf.put((byte) 0);
     }
   }
   // QQ号码个数
   if (receiverQQ == null) buf.put((byte) 0);
   else {
     buf.put((byte) receiverQQ.size());
     for (Integer qq : receiverQQ) buf.putInt(qq);
   }
   // 未知1字节
   buf.put((byte) 0x03);
   // 消息
   if (message == null) buf.putChar((char) 0);
   else {
     buf.putChar((char) message.length);
     // 消息
     buf.put(message);
   }
 }
示例#24
0
 /**
  * Puts a char into this hasher.
  *
  * @param c A char.
  * @return This instance.
  */
 MessageDigestHasher putChar(char c) {
   scratch.putChar(c);
   return update(Character.SIZE / Byte.SIZE);
 }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!isArray(obj)) {
     return super.write(buff, obj);
   }
   Class<?> type = obj.getClass().getComponentType();
   Integer classId = getCommonClassId(type);
   if (classId != null) {
     if (type.isPrimitive()) {
       if (type == byte.class) {
         byte[] data = (byte[]) obj;
         int len = data.length;
         if (len <= 15) {
           buff.put((byte) (TAG_BYTE_ARRAY_0_15 + len));
         } else {
           buff.put((byte) TYPE_ARRAY);
           buff.put((byte) classId.intValue());
           DataUtils.writeVarInt(buff, len);
         }
         buff = DataUtils.ensureCapacity(buff, data.length);
         buff.put(data);
         return buff;
       }
       buff.put((byte) TYPE_ARRAY);
       buff.put((byte) classId.intValue());
       int len = Array.getLength(obj);
       DataUtils.writeVarInt(buff, len);
       buff = DataUtils.ensureCapacity(buff, 8 * len);
       for (int i = 0; i < len; i++) {
         if (type == boolean.class) {
           buff.put((byte) (((boolean[]) obj)[i] ? 1 : 0));
         } else if (type == char.class) {
           buff.putChar(((char[]) obj)[i]);
         } else if (type == short.class) {
           buff.putShort(((short[]) obj)[i]);
         } else if (type == int.class) {
           buff.putInt(((int[]) obj)[i]);
         } else if (type == float.class) {
           buff.putFloat(((float[]) obj)[i]);
         } else if (type == double.class) {
           buff.putDouble(((double[]) obj)[i]);
         } else {
           buff.putLong(((long[]) obj)[i]);
         }
       }
       return buff;
     }
     buff.put((byte) TYPE_ARRAY);
     buff.put((byte) classId.intValue());
   } else {
     buff.put((byte) TYPE_ARRAY);
     buff.put((byte) -1);
     String c = type.getName();
     buff = StringDataType.INSTANCE.write(buff, c);
   }
   Object[] array = (Object[]) obj;
   int len = array.length;
   DataUtils.writeVarInt(buff, len);
   for (Object x : array) {
     buff = elementType.write(buff, x);
   }
   return buff;
 }
  /** Get the data in the map as a byte buffer */
  public ByteBuffer getData() {
    ByteBuffer buf = ByteBuffer.allocate(getLength());

    // write the header
    buf.putShort(getFormat());
    buf.putShort((short) getLength());
    buf.putShort(getLanguage());

    // write the various values
    buf.putShort((short) (getSegmentCount() * 2));
    buf.putShort(getSearchRange());
    buf.putShort(getEntrySelector());
    buf.putShort(getRangeShift());

    // write the endCodes
    for (Iterator i = segments.keySet().iterator(); i.hasNext(); ) {
      Segment s = (Segment) i.next();
      buf.putShort((short) s.endCode);
    }

    // write the pad
    buf.putShort((short) 0);

    // write the startCodes
    for (Iterator i = segments.keySet().iterator(); i.hasNext(); ) {
      Segment s = (Segment) i.next();
      buf.putShort((short) s.startCode);
    }

    // write the idDeltas for segments using deltas
    for (Iterator i = segments.keySet().iterator(); i.hasNext(); ) {
      Segment s = (Segment) i.next();

      if (!s.hasMap) {
        Integer idDelta = (Integer) segments.get(s);
        buf.putShort(idDelta.shortValue());
      } else {
        buf.putShort((short) 0);
      }
    }

    // the start of the glyph array
    int glyphArrayOffset = 16 + (8 * getSegmentCount());

    // write the idRangeOffsets and maps for segments using maps
    for (Iterator i = segments.keySet().iterator(); i.hasNext(); ) {
      Segment s = (Segment) i.next();

      if (s.hasMap) {
        // first set the offset, which is the number of bytes from the
        // current position to the current offset
        buf.putShort((short) (glyphArrayOffset - buf.position()));

        // remember the current position
        buf.mark();

        // move the position to the offset
        buf.position(glyphArrayOffset);

        // now write the map
        char[] map = (char[]) segments.get(s);
        for (int c = 0; c < map.length; c++) {
          buf.putChar(map[c]);
        }

        // reset the data pointer
        buf.reset();

        // update the offset
        glyphArrayOffset += map.length * 2;
      } else {
        buf.putShort((short) 0);
      }
    }

    // make sure we are at the end of the buffer before we flip
    buf.position(glyphArrayOffset);

    // reset the data pointer
    buf.flip();

    return buf;
  }
示例#27
0
 public void putString(String s) {
   grow(s.length() * Character.SIZE + Short.SIZE);
   int len = s.length();
   byteBuffer.putShort((short) len);
   for (int i = 0; i < len; i++) byteBuffer.putChar(s.charAt(i));
 }
示例#28
0
文件: MapInfo.java 项目: burto/mkgmap
 void write(ByteBuffer os) throws IOException {
   os.putInt(hexMapname);
   os.putChar(productId);
   os.putChar(familyId);
   os.putInt(mapname);
 }