/**
   * Writes a string to the specified DataOutput using <a
   * href="DataInput.html#modified-utf-8">modified UTF-8</a> encoding in a machine-independent
   * manner.
   *
   * <p>First, two bytes are written to out as if by the <code>writeShort</code> method giving the
   * number of bytes to follow. This value is the number of bytes actually written out, not the
   * length of the string. Following the length, each character of the string is output, in
   * sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the
   * counter <code>written</code> is incremented by the total number of bytes written to the output
   * stream. This will be at least two plus the length of <code>str</code>, and at most two plus
   * thrice the length of <code>str</code>.
   *
   * @param str a string to be written.
   * @param out destination to write to
   * @return The number of bytes written out.
   * @exception IOException if an I/O error occurs.
   */
  static int writeUTF(String str, DataOutput out) throws IOException {
    int strlen = str.length();
    int utflen = 0;
    int c, count = 0;

    /* use charAt instead of copying String to char array */
    for (int i = 0; i < strlen; i++) {
      c = str.charAt(i);
      if ((c >= 0x0001) && (c <= 0x007F)) {
        utflen++;
      } else if (c > 0x07FF) {
        utflen += 3;
      } else {
        utflen += 2;
      }
    }

    if (utflen > 65535)
      throw new IllegalArgumentException("encoded string too long: " + utflen + " bytes");

    byte[] bytearr = null;
    if (out instanceof DataOutputStream) {
      DataOutputStream dos = (DataOutputStream) out;
      if (dos.bytearr == null || (dos.bytearr.length < (utflen + 2)))
        dos.bytearr = new byte[(utflen * 2) + 2];
      bytearr = dos.bytearr;
    } else {
      bytearr = new byte[utflen + 2];
    }

    bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF);
    bytearr[count++] = (byte) ((utflen >>> 0) & 0xFF);

    int i = 0;
    for (i = 0; i < strlen; i++) {
      c = str.charAt(i);
      if (!((c >= 0x0001) && (c <= 0x007F))) break;
      bytearr[count++] = (byte) c;
    }

    for (; i < strlen; i++) {
      c = str.charAt(i);
      if ((c >= 0x0001) && (c <= 0x007F)) {
        bytearr[count++] = (byte) c;

      } else if (c > 0x07FF) {
        bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
        bytearr[count++] = (byte) (0x80 | ((c >> 6) & 0x3F));
        bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
      } else {
        bytearr[count++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
        bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
      }
    }
    out.write(bytearr, 0, utflen + 2);
    return utflen + 2;
  }
  /**
   * Constructor with a <code>DataOutputStream</code>.
   *
   * @param out the underlying <code>DataOutputStream</code>
   * @exception IOException gets thrown when an IO error occurs.
   */
  public DataSerializationOutputStream(DataOutputStream out) throws IOException {
    super(out);
    int bufferSize = out.bufferSize();
    if (bufferSize <= 0) {
      bufferSize = IOProperties.TYPED_BUFFER_SIZE;
    }
    BYTE_BUFFER_SIZE =
        DataSerializationInputStream.typedBufferSize(bufferSize, Constants.SIZEOF_BYTE);
    CHAR_BUFFER_SIZE =
        DataSerializationInputStream.typedBufferSize(bufferSize, Constants.SIZEOF_CHAR);
    SHORT_BUFFER_SIZE =
        DataSerializationInputStream.typedBufferSize(bufferSize, Constants.SIZEOF_SHORT);
    INT_BUFFER_SIZE =
        DataSerializationInputStream.typedBufferSize(bufferSize, Constants.SIZEOF_INT);
    LONG_BUFFER_SIZE =
        DataSerializationInputStream.typedBufferSize(bufferSize, Constants.SIZEOF_LONG);
    FLOAT_BUFFER_SIZE =
        DataSerializationInputStream.typedBufferSize(bufferSize, Constants.SIZEOF_FLOAT);
    DOUBLE_BUFFER_SIZE =
        DataSerializationInputStream.typedBufferSize(bufferSize, Constants.SIZEOF_DOUBLE);

    if (!NO_ARRAY_BUFFERS) {
      initArrays();
    }

    if (TIME_DATA_SERIALIZATION) {
      timer = new SerializationTimer(toString());
    } else {
      timer = null;
    }
  }
Example #3
0
  public static void main(String[] args) throws Exception {
    // primitive type 데이터 출력하기
    DataOutputStream out = new DataOutputStream("./test/ex05.test03.dat");

    // 성적 데이터 출력하기
    String name = "홍길동";
    int kor = 100;
    int eng = 90;
    int math = 80;

    out.writeUTF(name);
    out.writeInt(kor);
    out.writeInt(eng);
    out.writeInt(math);

    out.close();
    System.out.println("실행완료");
  }
Example #4
0
  /**
   * POST pData to pUrl
   *
   * @return the response Customized for sending pngs with name="spectrum[photo]" ... possibly lead
   *     if we switch to ImageIO: http://pastebin.com/f6783c437
   */
  public String postData(URL pUrl, byte[] pData, String filename) {
    // http://wiki.processing.org/w/Saving_files_to_a_web_server
    try {
      URLConnection c = pUrl.openConnection();
      c.setDoOutput(true);
      c.setDoInput(true);
      c.setUseCaches(false);

      // set request headers
      final String boundary = "AXi93A";
      c.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

      // open a stream which can write to the url
      DataOutputStream dstream = new DataOutputStream(c.getOutputStream());

      // write content to the server, begin with the tag that says a content element is comming
      dstream.writeBytes("--" + boundary + "\r\n");

      // describe the content
      // dstream.writeBytes("Content-Disposition: form-data; name=\"data\"; filename=\"whatever\"
      // \r\nContent-Type: text/json\r\nContent-Transfer-Encoding: binary\r\n\r\n");
      dstream.writeBytes(
          "Content-Disposition: form-data; name=\"photo\"; filename=\""
              + filename
              + "\" \r\nContent-Type: image/png\r\nContent-Transfer-Encoding: binary\r\n\r\n");
      dstream.write(pData, 0, pData.length);

      // close the multipart form request
      dstream.writeBytes("\r\n--" + boundary + "--\r\n\r\n");
      dstream.flush();
      dstream.close();

      // read the output from the URL
      BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
      StringBuilder sb = new StringBuilder(in.readLine());
      String s = in.readLine();
      while (s != null) {
        s = in.readLine();
        sb.append(s);
      }
      return sb.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  /**
   * UPDATE
   *
   * @param url
   * @param data the request body
   * @throws IOException
   */
  public String post(String url, String data) throws IOException {

    HttpConnection hcon = null;
    DataInputStream dis = null;
    DataOutputStream dos = null;
    StringBuffer responseMessage = new StringBuffer();

    try {
      int redirectTimes = 0;
      boolean redirect;

      do {
        redirect = false;
        // an HttpConnection with both read and write access
        hcon = getConnection(url, Connector.READ_WRITE);
        // set the request method to POST
        hcon.setRequestMethod(HttpConnection.POST);
        // overwrite content type to be form based
        hcon.setRequestProperty("Content-Type", "application/json");
        // set message length
        if (data != null) {
          hcon.setRequestProperty("Content-Length", "" + data.length());
        }

        if (data != null) {
          // obtain DataOutputStream for sending the request string
          dos = hcon.openDataOutputStream();
          byte[] request_body = data.getBytes();
          // send request string to server
          for (int i = 0; i < request_body.length; i++) {
            dos.writeByte(request_body[i]);
          } // end for( int i = 0; i < request_body.length; i++ )
          dos.flush(); // Including this line may produce
          // undesiredresults on certain devices
        }

        // obtain DataInputStream for receiving server response
        dis = new DataInputStream(hcon.openInputStream());
        // retrieve the response from server
        int ch;
        while ((ch = dis.read()) != -1) {
          responseMessage.append((char) ch);
        } // end while( ( ch = dis.read() ) != -1 ) {
        // check status code
        int status = hcon.getResponseCode();
        switch (status) {
          case HttpConnection.HTTP_OK: // Success!
            break;
          case HttpConnection.HTTP_TEMP_REDIRECT:
          case HttpConnection.HTTP_MOVED_TEMP:
          case HttpConnection.HTTP_MOVED_PERM:
            // Redirect: get the new location
            url = hcon.getHeaderField("location");
            System.out.println("Redirect: " + url);

            if (dis != null) dis.close();
            if (hcon != null) hcon.close();
            hcon = null;
            redirectTimes++;
            redirect = true;
            break;
          default:
            // Error: throw exception
            hcon.close();
            throw new IOException("Response status not OK:" + status);
        }

        // max 5 redirects
      } while (redirect == true && redirectTimes < 5);

      if (redirectTimes == 5) {
        throw new IOException("Too much redirects");
      }
    } catch (Exception e) {
      e.printStackTrace();
      responseMessage.append("ERROR");
    } finally {
      // free up i/o streams and http connection
      try {
        if (hcon != null) hcon.close();
        if (dis != null) dis.close();
        if (dos != null) dos.close();
      } catch (IOException ioe) {
        ioe.printStackTrace();
      } // end try/catch
    } // end try/catch/finally
    return responseMessage.toString();
  }