我有一个文本文件,它包含大量的图像网址逐行。我需要获取Java代码以自动提取这些图像并将这些图像保存到文件中。我知道如何从单个URL保存图像,但我如何修改代码以执行多线程?我想用原始文件名将所有图像放在一个文件夹下。我试图谷歌了很多代码,但一切都是失败的。请帮我找到一个解决方案。将不胜感激。使用java从100个图像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'([读/加载图像](http://docs.oracle.com /javase/tutorial/2d/images/loadimage.html)和[编写/保存图像](http://docs.oracle.com/javase/tutorial/2d/images/saveimage.html))。使用某种'ExecutorService',可能是一个固定池服务,从文本文件中加载所有条目,为每个条目添加一个“任务”到'ExecutorService'。运行,直到完成(可能使用像'invokeAll') – MadProgrammer