Reading binary file from URLConnection

前端 未结 2 1947
温柔的废话
温柔的废话 2020-12-01 08:22

I\'m trying to read a binary file from a URLConnection. When I test it with a text file it seems to work fine but for binary files it doesn\'t. I\'m using the following mime

相关标签:
2条回答
  • 2020-12-01 08:35

    If you are trying to read a binary stream, you should NOT wrap the InputStream in a Reader of any kind. Read the data into a byte array buffer using the InputStream.read(byte[], int, int) method. Then write from the buffer to a FileOutputStream.

    The way you are currently reading/writing the file will convert it into "characters" and back to bytes using your platform's default character encoding. This is liable to mangle binary data.

    (There is a charset (LATIN-1) that provides a 1-to-1 lossless mapping between bytes and a subset of the char value-space. However this is a bad idea even when the mapping works. You will be translating / copying the binary data from byte[] to char[] and back again ... which achieves nothing in this context.)

    0 讨论(0)
  • 2020-12-01 08:50

    This is how I do it,

    input = connection.getInputStream();
    byte[] buffer = new byte[4096];
    int n;
    
    OutputStream output = new FileOutputStream( file );
    while ((n = input.read(buffer)) != -1) 
    {
        output.write(buffer, 0, n);
    }
    output.close();
    
    0 讨论(0)
提交回复
热议问题