package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class testFile {
//public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
// download("http://avatar.csdn.net/1/3/B/1_li1325169021.jpg", "1_li1325169021.jpg","d:\\image\\");
// }
//链接url下载图片
public static void download(String urlString, String filename,String savePath) throws Exception {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5*1000);
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
File sf=new File(savePath);
if(!sf.exists()){
sf.mkdirs();
}
OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
public static void main(String[] args) {
try {
// 将D:/test.txt文件读取到输入流中
InputStream input = new FileInputStream("C:/Users/Admin/Desktop/路径.txt");
InputStream inputTwo = new FileInputStream("C:/Users/Admin/Desktop/文件名.txt");
// 创建BufferedReader,以gb2312的编码方式读取文件
BufferedReader reader = new BufferedReader(new InputStreamReader(input, "utf-8"));
BufferedReader readerTwo = new BufferedReader(new InputStreamReader(inputTwo, "utf-8"));
List fileUrl = new ArrayList();//图片路径List
List fileUrlTwo = new ArrayList();//图片名称List
String line = null;
String lineTwo = null;
// 按行读取文本,直到末尾(一般都这么写)
while ((line = reader.readLine()) != null) {
// 打印当前行字符串
fileUrl ff = new fileUrl();
ff.setPathUrl(line);
fileUrl.add(ff);
}
while ((lineTwo = readerTwo.readLine()) != null) {
// 打印当前行字符串
lineTwo = lineTwo.substring(lineTwo.lastIndexOf("/")+1,lineTwo.length());
fileUrlTwo fg = new fileUrlTwo();
fg.setFileName(lineTwo);
fileUrlTwo.add(fg);
}
String savePath = "D:\\text\\";//保存本地url
for(int i=0; i<246;i++){//下载条数,现给的死值,可根据list.size()获取
String fileurl = fileUrl.get(i).getPathUrl();//下载路径
String pathName = fileUrlTwo.get(i).getFileName();//图片名称
System.out.println("图片下载Url:"+fileurl+"图片保存对应名称:"+pathName);
download(fileurl,pathName,savePath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}