下载后,文件变成白色
。
下载代码:
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;
});
}
答案 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();
}
});
}