java Android:如何在android中下载文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5881774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: How to download file in android?
提问by Kris
I'm trying to download a file from a URL. I have the following code.
我正在尝试从 URL 下载文件。我有以下代码。
package com.example.downloadfile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class DownloadFile extends Activity {
private static String fileName = "al.jpg";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("This is download file program... ");
try {
//this is the file you want to download from the remote server
String path ="http://www.fullissue.com/wp-content/uploads/2010/12/Adam-Lambert.jpg";
//this is the name of the local file you will create
String targetFileName = "al.jpg";
boolean eof = false;
URL u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH_op = Environment.getExternalStorageDirectory() + "/download/" + targetFileName;
tv.append("\nPath > " + PATH_op);
FileOutputStream f = new FileOutputStream(new File(PATH_op));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
tv.append("\nAnother append!");
this.setContentView(tv);
}
}
Can someone tell me what's wrong with this code. I'm not able to see the file I'm supposed to download. I'm new to java and android dev, many thanks for any help. :)
谁能告诉我这段代码有什么问题。我看不到我应该下载的文件。我是 java 和 android dev 的新手,非常感谢您的帮助。:)
回答by CommonsWare
You are doing network I/O on the main application thread. At best, this will freeze your UI while the download is going on. At worst, you activity will crash with an "Application Not Responding" (ANR) dialog.
You are trying to write to a directory (
download/
) on external storage that might not exist. Please create the directory first.Please consider switching to using
Log.e()
for your error logging, as I do not know ifprintStackTrace()
works on Android.
您正在主应用程序线程上执行网络 I/O。充其量,这会在下载过程中冻结您的 UI。最坏的情况是,您的活动将因“应用程序无响应”(ANR) 对话框而崩溃。
您正在尝试写入
download/
可能不存在的外部存储上的目录 ( )。请先创建目录。请考虑切换到
Log.e()
用于错误日志记录,因为我不知道是否printStackTrace()
适用于 Android。
Also, make sure that you have the WRITE_EXTERNAL_STORAGE
permission and that you are using adb logcat
, DDMS, or the DDMS perspective in Eclipse to examine LogCat and look for the error messages you are trying to log.
此外,请确保您有WRITE_EXTERNAL_STORAGE
权限并且您正在adb logcat
Eclipse中使用、DDMS 或 DDMS 透视图来检查 LogCat 并查找您尝试记录的错误消息。
回答by Saman Abdolmohammadpour
firstly, you should add permissions to AndroidManifest.xml:
首先,您应该向 AndroidManifest.xml 添加权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
Secondly, add this code, so that if the folder doesn't exist, it checks and creates the folder:
其次,添加此代码,以便如果文件夹不存在,它会检查并创建文件夹:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/download");
if(!dir.exists()) {
dir.mkdirs();
}
Thirdly, as Commons Ware said, downloading on the main thread is not a good practice; you should implement it on a new thread; because while downloading, the main thread is busy for downloading the file. If the waiting time be more than expected the system will generate "Not responding" error.
第三,正如Commons Ware所说,在主线程上下载不是一个好习惯;你应该在一个新线程上实现它;因为在下载时,主线程正忙于下载文件。如果等待时间超过预期,系统将产生“无响应”错误。
In order to do that you can use "TaskAsync" or "IntentService" or even making a new thread.
为此,您可以使用“ TaskAsync”或“ IntentService”,甚至创建一个新线程。
As you said you are new to java, I suggest using "TaskAsync", as it is very straightforward and easy.
正如您所说,您是 Java 新手,我建议使用“ TaskAsync”,因为它非常简单明了。
回答by lyy
the lib will be help you
lib 会帮助你
https://github.com/AriaLyy/Aria
https://github.com/AriaLyy/Aria
download file only one code
下载文件只有一个代码
Aria.download(this)
.load(DOWNLOAD_URL)
.setDownloadPath(DOWNLOAD_PATH) //file save path
.add();
get download state
获取下载状态
@Download.onPre(DOWNLOAD_URL)
protected void onPre(DownloadTask task) {}
@Download.onTaskStart
void taskStart(DownloadTask task) {}
@Download.onTaskRunning
protected void running(DownloadTask task) {}
@Download.onTaskResume
void taskResume(DownloadTask task) {}
@Download.onTaskStop
void taskStop(DownloadTask task) {}
@Download.onTaskCancel
void taskCancel(DownloadTask task) {}
@Download.onTaskFail
void taskFail(DownloadTask task) {}
@Download.onTaskComplete
void taskComplete(DownloadTask task) {}
@Download.onNoSupportBreakPoint
public void onNoSupportBreakPoint(DownloadTask task) {}