java下载linux服务器根路径上的一张图片到本地java代码
时间: 2024-06-08 14:07:00 浏览: 61
你可以使用Java的URLConnection和InputStream来下载文件。以下是一个示例代码:
```java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class DownloadImage {
public static void main(String[] args) {
String imageUrl = "http://example.com/image.jpg";
String destinationFile = "/path/to/save/image.jpg";
try {
URL url = new URL(imageUrl);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int length;
FileOutputStream outputStream = new FileOutputStream(destinationFile);
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
System.out.println("Image downloaded successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请将imageUrl替换为要下载的图像的URL,并将destinationFile替换为要将图像保存到的本地路径。
阅读全文