javaweb采用绝对路径从网上下载图片
时间: 2023-09-13 17:04:00 浏览: 48
在Java Web开发中,可以使用绝对路径从网上下载图片。以下是一个简单的Java代码示例,用于将网上的图片下载到本地:
```java
import java.io.*;
import java.net.URL;
public class ImageDownloader {
public static void main(String[] args) {
String imageUrl = "https://example.com/image.jpg";
String destinationFile = "C:/images/image.jpg";
try {
// 创建URL对象
URL url = new URL(imageUrl);
// 打开连接
InputStream is = url.openStream();
// 读取数据并写入文件
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
// 关闭流
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,imageUrl 是要下载的图片的URL地址,destinationFile 是要保存到的本地文件路径。可以根据实际情况修改这些路径。这个示例中使用的是绝对路径,因此需要确保指定的路径存在并且有写入权限。