在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的值。