在Android中,可以使用以下幾種方式實(shí)現(xiàn)文件下載功能:
public class FileDownloader {
public static void downloadFile(String fileUrl, String destinationPath) {
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(destinationPath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用方法:
FileDownloader.downloadFile("http://example.com/file.txt", "/sdcard/file.txt");
public class FileDownloader {
public static void downloadFile(Context context, String fileUrl, String fileName) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(fileUrl);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
long downloadId = downloadManager.enqueue(request);
}
}
需要添加以下權(quán)限到AndroidManifest.xml文件中:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
使用方法:
FileDownloader.downloadFile(context, "http://example.com/file.txt", "file.txt");