帮忙写一个java下载功能
时间: 2023-05-30 18:07:39 浏览: 50
以下是一个使用Java编写的简单文件下载功能的示例代码:
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class FileDownload {
public static void main(String[] args) throws IOException {
String fileUrl = "https://example.com/examplefile.pdf";
String saveDir = "C:/Downloads/";
downloadFile(fileUrl, saveDir);
}
public static void downloadFile(String fileUrl, String saveDir) throws IOException {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
int fileSize = conn.getContentLength();
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
FileOutputStream out = new FileOutputStream(saveDir + getFileName(fileUrl));
byte[] buffer = new byte[1024];
int bytesRead = 0;
int totalBytesRead = 0;
while ((bytesRead = in.read(buffer, 0, 1024)) != -1) {
out.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
int percentage = (int) ((totalBytesRead * 100) / fileSize);
System.out.println("Downloaded " + percentage + "%");
}
out.close();
in.close();
System.out.println("File downloaded to " + saveDir);
}
public static String getFileName(String fileUrl) {
int index = fileUrl.lastIndexOf("/");
return fileUrl.substring(index + 1);
}
}
```
该代码使用URLConnection建立与文件URL的连接,并使用BufferedInputStream从连接中读取数据。每次读取1024个字节的数据,并将其写入FileOutputStream中。该代码还计算文件大小,并在下载时显示下载进度。最后,该代码使用getFileName方法从文件URL中提取文件名,并将其保存到指定目录中。