1. Java 图片爬虫,制作 .jar 文件
spider.java
spider.java
高清图片api : https://www.xwboke.cn/api/api.php
,每请求一次,会更换一张高清大图。
API1:
API2
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class spider{
public static void main(String[] args) throws Exception{
long start = System.currentTimeMillis();
System.out.print("start:");
System.out.println(start);
for(int i=1;i<=5;i++){
String url="https://www.xwboke.cn/api/api.php";
getImg(url,i);
System.out.println("Finished"+i);
}
long end=System.currentTimeMillis();
System.out.println("run time: "+(end-start)/1000+" s");
}
private static void getImg(String u, int i){
URL url;
try{
url = new URL(u);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5*1000);
InputStream in = conn.getInputStream();
byte[] data = readInputStream(in);
File f = new File(i+".jpg");
FileOutputStream out = new FileOutputStream(f);
out.write(data);
out.close();
}catch(IOException e){
e.printStackTrace();
}
}
private static byte[] readInputStream(InputStream ins) throws IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = ins.read(buffer)) != -1){
out.write(buffer, 0, len);
}
ins.close();
return out.toByteArray();
}
}
编译: javac spider.java
执行:java spider
root@kali:~/Desktop# java spider
start:1536475728353
Finished1
Finished2
Finished3
Finished4
Finished5
run time: 19 s
root@kali:~/Desktop#
制作 jar 文件
jar cvf 5imgGet.jar spider.class
此时直接运行:java -jar 5imgGet.jar
会报错:
直接将jar文件解压开,查看其中的 META-INF/MANIFEST.MF 文件,
root@kali:~/Desktop/tmp# cat META-INF/MANIFEST.MF
Manifest-Version: 1.0
Created-By: 1.8.0_151 (Oracle Corporation)
root@kali:~/Desktop/tmp#
只有两行,在第三行添加 Main-Class: spider
,指定主类
保存后执行 :jar umf MANIFEST.MF 5imgGet.jar
这样,这个jar文件就可以执行了。
添加执行权限
reference : https://www.cnblogs.com/liang-io/p/9338184.html