java下载文件到本地
时间: 2023-09-25 08:14:37 浏览: 46
可以使用Java的URLConnection和InputStream来下载文件,以下是一个简单的示例代码:
```java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void downloadFile(String fileUrl, String saveFilePath) throws Exception {
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 successfully!");
}
public static void main(String[] args) {
String fileUrl = "https://example.com/sample.pdf";
String saveFilePath = "C:\\Downloads\\sample.pdf";
try {
downloadFile(fileUrl, saveFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们通过URL打开一个连接,然后获取输入流并将其写入文件输出流中,最后关闭输入输出流即可。你只需要修改`fileUrl`和`saveFilePath`参数即可下载其他文件。
阅读全文