0

我试图将字节数组转换为十六进制字符串。但我最终出现内存不足错误异常。我对此一无所知。

        private String byteArrayToHexString(byte[] array) {
        StringBuffer hexString = new StringBuffer();
        for (byte b : array) {
          int intVal = b & 0xff;
          if (intVal < 0x10)
            hexString.append("0");
          hexString.append(Integer.toHexString(intVal));
        }
        return hexString.toString();

谢谢你们的帮助

4

2 回答 2

0

发送前不转换 - 发送时转换

于 2012-05-15T14:55:32.490 回答
0

这是一个例子。您基本上想先连接到网络服务器,然后直接在输出流中将图像转换为十六进制字符串,以便字节直接发送到服务器,您不必先将整个图像转换为巨大的字符串然后将其推送到服务器。

byte[] array; // This is your byte array containing the image
URL url = new URL("http://yourwebserver.com/image-upload-or-whatever");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
    urlConnection.setDoOutput(true);
    urlConnection.setChunkedStreamingMode(0);

    OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
    // Now you have an output stream that is connected to the webserver that you can
    //  write the content into
    for (byte b : array) {
        // Get the ASCII character for the first and second digits of the byte
        int firstDigit = ((b >> 4) & 0xF) + '0';
        int nextDigit = (b & 0xF) + '0';
        out.write(firstDigit);
        out.write(nextDigit);
    }
    out.flush(); // ensure all data in the stream is sent
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in); // Read any response
} finally {
    urlConnection.disconnect();
}

我没有尝试过这段代码,但希望你明白这一点。

于 2012-05-15T14:59:19.727 回答