从URL下载文件并保存到手机存储涉及以下几个基础概念:
以下是一个使用Java和Android平台从URL下载文件并保存到手机存储的示例代码:
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadFileTask extends AsyncTask<String, Void, Void> {
private static final String TAG = "DownloadFileTask";
private String fileUrl;
private String fileName;
public DownloadFileTask(String fileUrl, String fileName) {
this.fileUrl = fileUrl;
this.fileName = fileName;
}
@Override
protected Void doInBackground(String... params) {
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage());
return null;
}
InputStream inputStream = connection.getInputStream();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
FileOutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
Log.d(TAG, "File downloaded successfully: " + file.getAbsolutePath());
} catch (Exception e) {
Log.e(TAG, "Error downloading file", e);
}
return null;
}
}
new DownloadFileTask("https://example.com/file.zip", "file.zip").execute();
AndroidManifest.xml
中声明了存储权限:AndroidManifest.xml
中声明了存储权限:ConnectivityManager
检查网络状态:ConnectivityManager
检查网络状态:通过以上步骤和注意事项,可以有效地从URL下载文件并保存到手机存储。
领取专属 10元无门槛券
手把手带您无忧上云