我正在尝试下载mp4文件,但未能这样做。大小为25 MB的文件在目标文件夹中显示为~20 KB的文件。这是我的代码:
public class DownloadStream {
private final String VIDEO_FOLDER = "StackoverflowQuestion";
private String URL;
private String title;
Context context;
File rootDirectory;
public DownloadStream(String URL, String title, Context context) {
this.URL = URL;
this.title = title;
this.context = context;
File filepath = Environment.getExternalStorageDirectory();
rootDirectory = new File(filepath, VIDEO_FOLDER);
if (!rootDirectory.exists()) {
rootDirectory.mkdir();
}
DownloadObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
}
});
}
Observable<String> DownloadObservable(){
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
java.net.URL url;
int contentLength;
int counter = 0;
int percentage;
try {
url = new URL(URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
contentLength = connection.getContentLength();
connection.setRequestMethod("GET");
connection.connect();
File file = new File(rootDirectory, title + ".mp4");
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte buffer[] = new byte[1024];
int byteCount = 0;
while (inputStream.read(buffer) > 0) {
byteCount = inputStream.read(buffer);
fileOutputStream.write(buffer, 0, byteCount);
counter = byteCount + counter;
percentage = byteCount / contentLength;
}
fileOutputStream.close();
subscriber.onCompleted();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
我做错了什么?有没有更好的方法来做我想做的事情?
答案 0 :(得分:0)
你读太多:
while (inputStream.read(buffer) > 0) { //Fill buffer once
byteCount = inputStream.read(buffer); //fill buffer again
读取两次但只写了一次缓冲区。
以这种方式尝试:
int byteCount = inputStream.read(buffer);
while (byteCount >= 0) {
fileOutputStream.write(buffer, 0, byteCount);
counter = byteCount + counter;
percentage = byteCount / contentLength;
byteCount = inputStream.read(buffer);
}