用java 代码怎么写一个文件下载
时间: 2023-03-14 12:46:11 浏览: 42
我可以提供一些示例代码,帮助你实现文件下载: import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;public class DownloadFile {
public static void main(String[] args) {
String fileUrl = "https://example.com/example.zip";
String saveDir = "C:/Downloads/";
try {
downloadFile(fileUrl, saveDir);
} catch (IOException ex) {
ex.printStackTrace();
}
} public static void downloadFile(String fileUrl, String saveDir) throws IOException {
URL url = new URL(fileUrl);
BufferedInputStream bis = new BufferedInputStream(url.openStream());
FileOutputStream fos = new FileOutputStream(saveDir);
byte[] buffer = new byte[1024];
int count = 0;
while ((count = bis.read(buffer, 0, 1024)) != -1) {
fos.write(buffer, 0, count);
}
fos.close();
bis.close();
}
}