七度手机站

Java图片下载工具

Java图片下载工具

版本: 大小:10K

类别:编程开发 时间:2023-09-01

请使用电脑访问此页面下载

今天站长给大家带来Java图片下载工具,站长最近从网上找了一批美女图片的资源,不过这些被打包成CVS文件,但是站长觉得处理CVS有点麻烦,想想还是处理txt比较简单。下面就是使用Java下载图片方法啦。不过这个代码有个小问题,就是我使用的文件名都是jpg。不过图片都是公用的,没什么关系,如果是想要下载其它图片格式的话,就需要先获取后缀名哦。

Java代码

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class main {
	public static void main(String[] args) {
		String path = "d:/tt/pic/";
		String piclist = "d:/tt/pic_data.txt";
		File file = new File(piclist);
		// String outfile = "d:/tt/outfile.txt";
		try {
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			// BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outfile)));
			String line = null;
			int i = 1;
			Pattern p = Pattern.compile("http:.*?\\.(jpg|png|gif|jpeg)");

			while ((line = br.readLine()) != null) {
				if (checkurl(line)) {
					Matcher m = p.matcher(line);
					if (m.find()) {
						System.out.println("第" + i + "张:" + m.group(0));
						downloadPicture(m.group(0), path + i + ".jpg");
						i = i + 1;
					}
				}

			}
			System.out.println(i);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println();

	}

	public static boolean checkurl(String string) {
		if (string.indexOf("http") < 0) { return false; } return true; } 
private static void downloadPicture(String urlList, String path) {
 URL url = null; 
try { 
url = new URL(urlList); DataInputStream dataInputStream = new DataInputStream(url.openStream());
 FileOutputStream fileOutputStream = new FileOutputStream(new File(path)); ByteArrayOutputStream output = new ByteArrayOutputStream();
 byte[] buffer = new byte[1024]; 
int length; 
while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			fileOutputStream.write(output.toByteArray());
			dataInputStream.close();
			fileOutputStream.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
同类推荐
精品推荐