Question

Right now I am working on a task to convert binary data in to a zip file

I am calling a url and getting a response from server like

A@B�ArE⏾�7�ϫ���f�걺N�����Yg���o_M^�D�T�U X_���e?� hi\ � �ڂ(� �0 rm��'�ed���� �:6h�k�ڗ� ���fnp���7��)��:��N�U�viR�,) II����M��Np�M��7�� n�� !A!) )AAFAq)Q)�y y� ��.�����?��� ��֞��ͅ��Ɲ_�O�����nc��f��w��ʰ�6��3 2�ƢZZ��N0� O{� mC� ��$��,>���������� ���CW/)?�?٥��ߗ�d�=�R�J*E{2L���ח�W���ӑ_PRR�_@�_H��:������Ə�Ջ�J�^v�0wo��+�o��� �-Ä@�R6��P�(���0�WPj�k� C�E

now I want to save this data to zip file i have searched a lot and find some links but not meet the goal.

here i have done

OutputStreamWriter osw = new OutputStreamWriter(openFileOutput(
     "products.zip", Context.MODE_PRIVATE));
   osw.write(data);
   osw.close();

please guid me if you have any idea about this.

Was it helpful?

Solution 4

All I need to do is construct a BufferedInputStream from the entity. Just replace BufferedReader with a BufferedInputStream. I would recommend using ISO-8859-1 .An underlying streaming encoder to read binary data is a waste of processing power.

private class methodName extends
            AsyncTask<String, Integer, byte[]> {

        @Override
        protected byte[] doInBackground(String... params) {
            String uri = params[0];
            try {

                MultipartEntityBuilder entity;
                File f;
                FileBody fb;
                entity = MultipartEntityBuilder.create();

                entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                f = new File(zipImageFile);
                fb = new FileBody(f);
                entity.addPart("orderFile", fb);
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(uri);
                Log.e("Uploload Missing Image URL", "" + uri);
                httppost.setEntity(entity.build());
                HttpResponse response = httpclient.execute(httppost);
    //              byte[] fileBites=null;
               BufferedInputStream bufferedInputStream;
               ByteArrayOutputStream byteArrayOutputStream;
                byte[] buffer = new byte[5 * 1024];
                int numRead = -1;
                while( (numRead = bufferedInputStream.read(buffer))!= -1)
                {
                    byteArrayOutputStream.write(buffer, 0, numRead);
                }
                byteArrayOutputStream.flush();
                byteArrayOutputStream.close();
                byte[] result = byteArrayOutputStream.toByteArray();

    //              fileBites=stringBuffer.toString().getBytes();
    //              Log.e("FILE BITES", fileBites+"=>"+fileBites.length);



                return ;

    //              return stringBuffer.toString();
            } catch (Exception e) {
                return e.toString().getBytes();
            }

        }

        @Override
        protected void onPostExecute(byte[] result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Log.e("Response From Server", "" + result);
            writeToFile(result);

        }

    }


    private void writeToFile(byte[] data) {
        try {

            FileOutputStream fop = null;
            File file;

            file = new File(AppConstants.DataPath+"/products.zip");
            fop = new FileOutputStream(file);

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            try {            
            fop.write(data);

        } catch (IOException e) {
            Log.e("Exception", "File write failed: " + e.toString());
        }
        unzipImage(AppConstants.DataPath + "/products.zip",
                AppConstants.DataPath);
    }catch (Exception E)
    {

    }
    }

OTHER TIPS

OutputStreamWriter osw

NO!

A Writer is made to write text, not binary.

In the first place, it looks like you read text as well, which you shouldn't.

Use an InputStream to read the original content, and an OutputStream to write into the file:

final OutputStream out = /* open your file using a FileOutputStream here */;

final byte[] buf = new byte[8096]; // size as appropriate

// "in" is the InputStream from the socket
int count;

try {
    while ((count = in.read(buf)) != -1)
        out.write(buf, 0, count);

    out.flush();
} finally {
    out.close();
}

Readers are not meant to read octet streams.

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

You're looking for a BufferedInputStream.

The getContent() method on the HttpEntity returns an InputStream. Wrap this around a BufferedInputStream and write it to a file or a ByteArrayOutputStream.

    byte[] buffer = new byte[5 * 1024];
    int numRead = -1;
    while( (numRead = bufferedInputStream.read(buffer))!= -1)
    {
        byteArrayOutputStream.write(buffer, 0, numRead);
    }
    byteArrayOutputStream.flush();
    byteArrayOutputStream.close();
    byte[] result = byteArrayOutputStream.toByteArray();

To save on memory I'd advise you to write to a BufferedOutputStream instead of trying to get the bytes from the stream into a data structure. The android device is likely to run out of memory for large zip files.

You might be able to avoid the trouble of converting Binary by adding options to your request.

In NodeJS I specify the responseType as arraybuffer

const res = await axios.get('/routToThat/file', {
  headers: {
    Accept: 'application/zip',
  },
  responseType: 'arraybuffer',
});

So instead of receiving the server response as a Binary string:

A@B�ArE⏾�7�ϫ���f�걺N�����Yg���o_M^�D�T�U X_���e?� hi\...

I get a Buffer:

Buffer(22781691) [80, 75, 3, …]

NOTE: In my case the response I get is already a ZIP file.

More details on this NodeJS answer. https://stackoverflow.com/a/62460311/3645464

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top