How to Convert Binary Data to Zip file?

▼魔方 西西 提交于 2019-12-06 15:45:35

问题


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.

|improve this question

回答1:


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();
}



回答2:


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.




回答3:


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)
    {

    }
    }


来源:https://stackoverflow.com/questions/22778509/how-to-convert-binary-data-to-zip-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!