java下载本地文件
时间: 2024-05-17 20:10:25 浏览: 103
在Java中下载本地文件可以通过java.net包中的URL和URLConnection类来实现。下面是一个简单的示例代码:
```java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class DownloadFile {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.pdf";
String saveDir = "C:/Downloads/";
String fileName = "file.pdf";
try {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(saveDir + fileName);
byte[] buffer = new byte[4096];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
System.out.println("文件已下载至" + saveDir + fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
该示例中使用了URL和URLConnection类打开网络连接,并获取输入流。然后利用FileOutputStream类创建输出流,将数据写入到本地文件中。注意要关闭输入输出流,并捕获异常。
阅读全文