java - 通过套接字读取 JPEG 流给出空字符

标签 java android sockets inputstream fileinputstream

我正在使用此代码通过 InputStream 读取 .jpg 文件,但我在一些文本后收到 NULNUL...n 流。我正在阅读此文件 link to file以及我收到的文件的链接,链接是 Written File link

    while ((ret = input.read(imageCharArray)) != -1) {
    packet.append(new String(imageCharArray, 0, ret));

    totRead += ret;
            imageCharArray = new char[4096];
       }


   file = new File(
     Environment.getExternalStorageDirectory()
       + "/FileName_/"
       + m_httpParser.filename + ".jpg");
   PrintWriter printWriter = new PrintWriter(file);
   // outputStream = new FileOutputStream(file);  //also Used FileoutputStream for writting
   // outputStream.write(packet.toString().getBytes());//
   // ,
   printWriter.write(packet.toString());
   // outputStream.close();
   printWriter.close();
 }

我也尝试过FileoutputStream,但也对此进行了hardlucj,正如我的代码中所评论的那样。

编辑 我也用过这个。我有一个内容长度字段,我正在读取和写入该字段

    byte[] bytes = new byte[1024];
int totalReadLength = 0;

// read untill we have bytes
while ((read = inputStream.read(bytes)) != -1
        && contentLength >= (totalReadLength)) {

    outputStream.write(bytes, 0, read);
    totalReadLength += read;
    System.out.println(" read size ======= "
            + read + " totalReadLength = "
            + totalReadLength);

}

最佳答案

String 不是二进制数据的容器,PrintWriter 也不是写入它的方法。摆脱所有、所有、字节和字符串之间的转换,反之亦然,只用输入和输出流传输字节:

while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

如果您需要限制从输入读取的字节数,则必须在调用 read() 之前执行此操作,并且还必须正确限制 read():

while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length: (int)(length-total))) > 0)
{
    total += count;
    out.write(buffer, 0, count);
}

关于java - 通过套接字读取 JPEG 流给出空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22245287/

相关文章:

sockets - 如何绑定(bind)到任何可用端口?

ios - 在 applicationWillTerminate 中发出套接字事件

java - 线性回归和 Java 日期

java - 为什么不能在 ArrayList<this> 中使用 this 作为泛型?

java - 为什么我的表中的数据无法更新?

android - AccountManager 返回空账户

android - 为什么 Activity 的 onBackPressed 没有被调用?

java - AssertThat 在日期比较中的用法

android - 切换 onCheckedChangedListner 不在工具栏菜单内注册点击

c++ - poll() 不标记可读数据