【问题标题】:How do you read from an InputStream in Java and convert to byte array?如何从 Java 中的 InputStream 读取数据并转换为字节数组?
【发布时间】:2014-06-13 13:08:41
【问题描述】:

我目前正在尝试从服务器响应中读取数据。我使用 Socket 连接到服务器,创建 http GET 请求,然后使用缓冲读取器读取数据。以下是压缩后的代码:

    Socket conn = new Socket(server, 80);
    //Request made here
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String response;
    while((response = inFromServer.readLine()) != null){
        System.out.println(response);
    }

我想读入数据,而不是作为字符串,作为字节数组,并将其写入文件。这怎么可能?非常感谢任何帮助,谢谢。

【问题讨论】:

标签: java sockets http file-io


【解决方案1】:

您需要使用ByteArrayOutputStream,执行以下代码:

Socket conn = new Socket(server, 80);
        //Request made here
        InputStream is = conn.getInputStream();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int readBytes = -1;

        while((readBytes = is.read(buffer)) > 1){
            baos.write(buffer,0,readBytes);
        }

        byte[] responseArray = baos.toByteArray();

【讨论】:

  • 非常感谢。这很有帮助。然而,我还有一个问题。因此,HTTP 响应的格式首先是标题,然后是文件内容。因此,为了制作一个大小合适的字节数组,我必须首先解析标题并获取信息,然后读取文件。你会如何建议这样做?
  • 鉴于您的问题不建议采用稍微不同的方法,首先将响应作为文本(2 部分)标题和内容阅读。使用getBytes() 将文本内容转换为字节数组
  • 我确实考虑过。将其作为文本而不是字节读取所需的时间会有所不同吗?因为我在这里的全部目的是计算下载速度,而我看过的任何人的代码都将文件下载为字节。
  • 时间会有几毫秒的细微差别。因此,如果您正在查看这种精度,那么您可能希望使用字节读取(进入 ByteArrayOutputStream)并检查字节数组的内容何时开始(通过将其转换为字符串或检查字节码相当于 Content-Length 等)。
  • 您认为无论如何我都可以将文件作为文本读取到标题末尾,然后继续读取为字节?也许有什么办法可以改变 InputStream 的位置,让它从 BufferedReader 停止的地方开始?
【解决方案2】:

如果你没有在你的项目中使用 Apache commons-io 库,我有一个非常简单的方法可以在不使用它的情况下做同样的事情..

   /*
     * Read bytes from inputStream and writes to OutputStream,
     * later converts OutputStream to byte array in Java.
     */
    public static byte[] toByteArrayUsingJava(InputStream is)
    throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int reads = is.read();

        while(reads != -1){
            baos.write(reads);
            reads = is.read();
        }

        return baos.toByteArray();

    }

【讨论】:

    【解决方案3】:

    使用纯 java:

        ByteArrayOutputStream output = new ByteArrayOutputStream();
    
        try(InputStream stream = new FileInputStream("myFile")) {
            byte[] buffer = new byte[2048];
            int numRead;
            while((numRead = stream.read(buffer)) != -1) {
                output.write(buffer, 0, numRead);
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    
        // and here your bytes
        byte[] myDesiredBytes = output.toByteArray();
    

    【讨论】:

      【解决方案4】:

      一种方法是使用 Apache commons-io IOUtils

      byte[] bytes = IOUtils.toByteArray(inputstream);
      

      【讨论】:

        猜你喜欢
        • 2013-08-14
        • 2010-11-18
        • 2011-10-05
        • 2012-09-26
        • 2011-01-10
        • 1970-01-01
        • 2021-12-19
        相关资源
        最近更新 更多