1
所以我一直在谷歌搜索如何下载图像,并没有得到很好的书面解释,只是代码示例。我不完全了解一些这个代码,这主要与下载图像从reddit与java错误
for (int b; (b = is.read()) != -1;) {
os.write(b);
}
有人能解释这上面的代码像我五岁,也是任何替代这种方法。
EDIT2
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Downloader {
static String path = "C:\\reddit\\";
public static void main(String[] args) {
connect();
}
private static void download(String imageURL, int i) {
InputStream is = null;
OutputStream os = null;
try {
URL url = new URL(imageURL);
is = url.openStream();
os = new FileOutputStream(path + i + ".jpg");
for (int b; (b = is.read()) != -1;) {
os.write(b);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void connect() {
try {
Document doc = Jsoup.connect("http://www.reddit.com/r/pics").get();
Elements url = doc.select("a");
int i = 0;
for (Element img : url) {
if (img.attr("href").startsWith("http://imgur.com/")) {
String image = img.attr("abs:href")+".jpg";
System.out.println(image);
i++;
System.out.println(i);
download(image, i);
}
}
} catch (IOException e) {
System.out.println("page scrape fail");
}
}
}
编辑 我发现我的输出是不正确的,它的写作重复,我将只是张贴我的控制台结果
http://imgur.com/f7rW2Of
1
http://imgur.com/f7rW2Of
2
http://imgur.com/35jpkez
3
http://imgur.com/35jpkez
4
http://imgur.com/IX9HMJG
5
http://imgur.com/IX9HMJG
6
http://imgur.com/B6MoDbT
7
http://imgur.com/B6MoDbT
8
http://imgur.com/XMtCUY9
9
http://imgur.com/XMtCUY9
10
http://imgur.com/UkbbiBl
11
http://imgur.com/UkbbiBl
12
http://imgur.com/YfLsCal
13
http://imgur.com/YfLsCal
14
http://imgur.com/9Q3CJtT
15
http://imgur.com/9Q3CJtT
16
http://imgur.com/Vt7sWTf
17
http://imgur.com/Vt7sWTf
18
http://imgur.com/hBUH5kS
19
http://imgur.com/hBUH5kS
20
http://imgur.com/gallery/OWQH0h6
21
http://imgur.com/gallery/OWQH0h6
22
http://imgur.com/a/hiJXI
23
http://imgur.com/a/hiJXI
24
显示一个实际的错误。是的,除了一次读取一个字节的效率低下之外,您看起来还不错。 –
您是否因为BufferedReader而一次读取1个字节?我刚刚删除了这个,我仍然没有看到任何改变。每个文件都是29-35kb,即使我更改为jpg,也无法查看。我再也没有错误了,我可以从reddit.com/r/pics页面下载所有27张图片,只是无法查看其中的任何图片。你能否真的写作部分 – gallly
他们都是JPG吗? –