java URL下载文件
时间: 2023-09-11 12:05:06 浏览: 41
可以使用以下代码下载文件:
```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 download(String fileUrl, String saveFilePath) throws IOException {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
try (InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(saveFilePath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
}
}
```
其中,`fileUrl` 是文件的 URL 地址,`saveFilePath` 是保存文件的路径。你可以在自己的代码中调用 `FileDownloader.download(fileUrl, saveFilePath)` 方法来下载文件。