我正在编写一个应用程序,只需单击一个按钮即可从URL下载文件。问题是,在(显然)成功下载后,我在SD卡中找不到文件。我甚至尝试过输出Context.fileList()字符串数组,但它什么也不包含(导致错误日志"No files created")。
我怎么能说下载已经完成了呢?好吧,我看到数据连接一按下按钮就会激活,并且只在3-4秒后松弛,在此期间,我假设它正在下载小于100KB的文件。
以下是main活动的代码:
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());
}
}
}请帮帮我!
发布于 2013-07-02 00:21:49
几件事:
Environment.getExternalStorageDirectory(); 不是保存文件的正确位置,您需要为其指定文件名。
Environment.getExternalStorageDirectory() + "/myfile.pdf";还要确保您在manifest.xml中具有以下权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />此外,不能保证onDestroy()会被调用,所以这不是一个检查的好地方。
最后,要在将设备连接到pc时查看文件,您可能需要让MediaScanner知道有一个新文件要索引。
保存文件后发送广播,以确保在MediaStore中拾取该文件
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);https://stackoverflow.com/questions/17408954
复制相似问题