用java写一个文件下载
时间: 2024-05-29 07:03:35 浏览: 15
以下是一个简单的 Java 文件下载示例:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void downloadFile(String fileUrl, String saveFilePath) throws IOException {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded to: " + saveFilePath);
}
public static void main(String[] args) {
String fileUrl = "https://example.com/file.pdf";
String saveFilePath = "C:/Downloads/file.pdf";
try {
downloadFile(fileUrl, saveFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个示例使用 `URL` 和 `URLConnection` 类来打开文件链接并获取输入流。然后,使用 `FileOutputStream` 类创建输出流,并将文件的内容从输入流写入输出流中。最后,关闭输入和输出流并打印出文件保存的路径。