java 单次下载文件链接
时间: 2023-09-30 07:07:19 浏览: 41
以下是使用 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 saveDir) throws IOException {
URL url = new URL(fileUrl);
BufferedInputStream inputStream = new BufferedInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(saveDir);
byte[] dataBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
inputStream.close();
fileOutputStream.close();
}
public static void main(String[] args) {
String fileUrl = "https://example.com/file.txt";
String saveDir = "/path/to/save/directory/file.txt";
try {
downloadFile(fileUrl, saveDir);
System.out.println("File downloaded successfully.");
} catch (IOException e) {
System.out.println("Error occurred while downloading the file: " + e.getMessage());
}
}
}
```
在这个示例中,我们使用 `URL` 类来打开文件链接,使用 `BufferedInputStream` 类来读取文件内容并将其写入本地文件,使用 `FileOutputStream` 类将文件写入本地目录。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)