【发布时间】:2015-06-21 05:19:43
【问题描述】:
我有一个文本文件,其中逐行包含大量图像 URL。我需要一个 Java 代码来自动提取这些图像并将这些图像保存到一个文件中。我知道如何从单个 URL 保存图像,但是如何修改代码以执行多线程?我想用原始文件名获取单个文件夹下的所有图像。我试图用谷歌搜索出许多代码,但一切都失败了。请帮我找到解决方案。我们将不胜感激。
我用来保存单张图片的代码是:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class SaveImageFromUrl {
public static void main(String[] args) throws Exception {
String imageUrl = "http://http://img.emol.com/2015/04/25/nepalterremoto02ok_2260.jpg";
String destinationFile = "/home/abc/image.jpg";
saveImage(imageUrl, destinationFile);
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
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();
}
}
【问题讨论】:
-
ImageIO.read和ImageIO.write(Reading/Loading an Image 和 Writing/Saving an Image)。使用某种ExecutorService,可能是一个固定池服务,从文本文件中加载所有条目,为每个条目添加一个“任务”到ExecutorService。运行直到全部完成(可能使用invokeAll之类的东西)