Android - 将字节数组写入OutputStreamWriter

时间:2012-07-18 14:03:41

标签: android string stream byte

我有一个通过网络服务上传照片的应用程序。过去,我将文件加载到流中,然后转换为Base64。然后我通过OutputStreamWriter的write()方法发布了结果字符串。现在,Web服务已经改变,它期望multipart / form-data,它不期望Base64。

所以不知怎的,我需要在没有转换的情况下发布这个文件的chararters。我确定我很接近,但我得到的只是内容长度下溢或溢出。奇怪的是,在调试器中,我可以看到我的缓冲区长度与我发布的字符串的长度相同。这就是我正在做的事情,希望足够的代码:

// conn is my connection
OutputStreamWriter dataStream = new OutputStreamWriter(conn.getOutputStream());

// c is my file
int bytesRead = 0;
long bytesAvailable = c.length();

while (bytesAvailable > 0) {
   byte[] buffer = new byte[Math.min(12288, (int)bytesAvailable)];
   bytesRead = fileInputStream.read(buffer, 0, Math.min(12288, (int)bytesAvailable));

   // assign the string if needed.
   if (bytesRead > 0) {
      bytesAvailable = fileInputStream.available();

      // I've tried many encoding types here.
      String sTmp = new String(buffer, "ISO-8859-1");
      // HERE'S the issue.  I can't just write the buffer,
      dataStream.write(sTmp);
      dataStream.flush();
// Yes there's more code, but this should be enough to show why I don't know what I'm doing!

1 个答案:

答案 0 :(得分:11)

更改

OutputStreamWriter dataStream = new OutputStreamWriter(conn.getOutputStream());

用这个

DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream()); 

并直接致电dataStream.write(buffer);

让我知道它的行为

编辑:根据评论编辑的答案