java写一个文件下载功能
时间: 2024-05-17 14:13:58 浏览: 14
你好,以下是Java实现文件下载功能的示例代码:
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
public class FileDownloader {
public static void downloadFile(String fileUrl, String destinationFilePath) throws IOException {
URL url = new URL(fileUrl);
BufferedInputStream inputStream = new BufferedInputStream(url.openStream());
FileOutputStream outputStream = new FileOutputStream(destinationFilePath);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
public static void main(String[] args) {
String fileUrl = "https://example.com/example.pdf";
String destinationFilePath = "/path/to/save/file/example.pdf";
try {
downloadFile(fileUrl, destinationFilePath);
System.out.println("File downloaded successfully!");
} catch (IOException e) {
System.out.println("Error downloading file: " + e.getMessage());
}
}
}
```
这个示例代码会下载一个PDF文件并保存到指定的路径。你可以根据需要修改文件的URL和目的地文件路径。