📅  最后修改于: 2023-12-03 15:37:56.235000             🧑  作者: Mango
在 Java 中,我们可以使用程序来从服务器 URL 中提取图像,并将其存储在本地文件夹中。这个过程需要使用 Java 的网络编程、流处理和文件处理知识。下面就详细介绍一下如何实现这个功能。
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class ImageDownload {
public static void main(String[] args) throws Exception {
String imageUrl = "https://www.example.com/image.jpg";
String destination = "C:/images/image.jpg"; // 保存的本地文件路径
URL url = new URL(imageUrl);
InputStream inputStream = url.openStream();
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = inputStream.read(buffer))) {
byteOutputStream.write(buffer, 0, n);
}
byteOutputStream.close();
inputStream.close();
byte[] imageBytes = byteOutputStream.toByteArray();
FileOutputStream fileOutputStream = new FileOutputStream(destination);
fileOutputStream.write(imageBytes);
fileOutputStream.close();
}
}
通过以上的代码,我们可以看到如何从服务器 URL 中提取图像并将其存储在本地文件夹中。这里使用了 Java 的网络编程、流处理和文件处理等知识,掌握了这些技能可以让我们更好地进行 Java 开发。