在Android中,可以使用以下代碼將文件下載并保存到本地:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
private void downloadFile(String url, String fileName) {
try {
URL downloadUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
String storagePath = Environment.getExternalStorageDirectory().toString();
File file = new File(storagePath, fileName);
FileOutputStream outputStream = new FileOutputStream(file);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
其中,url參數是要下載的文件的URL地址,fileName參數是要保存的文件名。該方法會將文件下載到Android設備上的默認存儲位置,通常是SD卡的根目錄。如果要將文件保存到其他位置,可以修改storagePath的值。