我正在编写一个应用程序,通过单击按钮从 URL 下载文件。问题是(显然)成功下载后,我在 SD 卡中找不到该文件。我什至尝试输出Context.fileList()
字符串数组,但它什么都不包含(导致错误日志“未创建文件”)。
我怎么能说下载完成了?好吧,我看到数据连接在按下按钮后立即激活,并且仅在 3-4 秒后放松,在此期间我假设它正在下载小于 100KB 的文件。
这是主要活动的代码:
package com.filedownloaddemo;
import java.io.File;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn;
// URL to download from
String url = "http://www.edco.ie/_fileupload/The%20Interlopers%20-%20A%20short%20story%20by%20Saki.pdf";
// file variable
File outputFile;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
// set Android policy
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// onClick handler for the button
public void download(View v) {
try {
outputFile = new File(Environment.getExternalStorageDirectory() + File.separator + "myfile.pdf");
DownloadHelper.downloadFile(url, outputFile);
} catch (Exception e) {
Log.d("DL_Error", e.getMessage());
}
if (this.fileList().length == 0) {
Log.d("DL_Error", "No files created.");
} else {
// write file names to Log
for (String s : this.fileList()) {
Log.d("Download", s);
}
}
}
}
这是下载的文件(取自该社区的答案之一):
package com.filedownloaddemo;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import android.util.Log;
public class DownloadHelper {
public static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(
outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch (Exception e) {
Log.d("DL_Error", e.getMessage());
}
}
}
请帮忙!