PDF文件下载后为空

时间:2018-10-01 09:36:21

标签: android file pdf retrofit2 downloading

下载后,文件变成白色 。
下载代码:

   public Single<File> download(String url, long formId) {
    return restService.downloadFile(url)
            .subscribeOn(Schedulers.io())
            .map(responseBodyResponse -> {
                String filename = String.valueOf(formId);
                long timeInMillis = Calendar.getInstance().getTimeInMillis();
                filename = filename.concat("_").concat(String.valueOf(timeInMillis)).concat(PDF);
                File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsoluteFile(), filename);
                BufferedSink sink = Okio.buffer(Okio.sink(file));
                // you can access body of response
                if (responseBodyResponse.body() != null) {
                    BufferedSource bufferedSource = responseBodyResponse.body().source();
                    sink.writeAll(bufferedSource);
                    sink.close();
                }
                return file;
            });
}

enter image description here 我做错了什么?

1 个答案:

答案 0 :(得分:0)

这种方法对我有用

private  final int MEGABYTE = 1024 * 1024;

public Single<File> download(String fileUrl, long formId) {
    return Single.create(emitter -> {
        try {
            String filename = String.valueOf(formId);
            long timeInMillis = Calendar.getInstance().getTimeInMillis();
            filename = filename.concat("_").concat(String.valueOf(timeInMillis)).concat(PDF);
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsoluteFile(), filename);
            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(file);

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
            emitter.onSuccess(file);
        } catch (FileNotFoundException e) {
            emitter.onError(e);
            e.printStackTrace();
        } catch (MalformedURLException e) {
            emitter.onError(e);
            e.printStackTrace();
        } catch (IOException e) {
            emitter.onError(e);
            e.printStackTrace();
        }
    });
}
相关问题