我应该如何将二进制文件发送到SD卡,例如图像或.apk



我用'com.loopj.android:android-async-http:1.4.9'发出http请求。我使用BinaryHttpResponseHandler来获取图像,但我想将其发送到SD卡。我的代码是:

AsyncHttpUtils.getBinary(url, new BinaryHttpResponseHandler(allowedContentTypes) {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
            Log.d(TAG,"getFile onSuccess"+binaryData.length);
            String tempPath = "Download";
            // 文件地址
            String filePath =  tempPath +"/"+ "oktest" + ".jpg";
            FileUtils fileUtils = new FileUtils();
            InputStream inputstream = new ByteArrayInputStream(binaryData);
            if (inputstream != null) {
                fileUtils.write2SDFromInput(filePath, inputstream);
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) {
            Log.d(TAG,"getFile onFailure");
        }
    });

如何将二进制文件发送到SD卡?

你不需要用ByteArrayInputStreamFileUtils,只需FileOutputStream即可。

AsyncHttpUtils.getBinary(url, new BinaryHttpResponseHandler(allowedContentTypes) {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
        Log.d(TAG,"getFile onSuccess "+binaryData.length);
        File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "yourFileName.jpg");
        try (FileOutputStream os = new FileOutputStream(file)) {
            os.write(binaryData);
            os.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) {
        Log.d(TAG,"getFile onFailure");
    }
});

相关内容

  • 没有找到相关文章

最新更新