publicclassDownLoadImageMBI {
privatestatic String URL = "http://xxxxx.com/uploads/";
publicstaticvoid main(String[] args) {
try {
readLineFile();
}catch(Exception e) {
e.printStackTrace();
}
}
publicstaticvoid readLineFile() {
List
try {
FileInputStreamin = new FileInputStream("c:\\33.txt");
InputStreamReaderinReader= newInputStreamReader(in,"UTF-8");
BufferedReaderbufReader= newBufferedReader(inReader);
Stringline= null;
while ((line = bufReader.readLine()) != null) {
list.add(line);
}
bufReader.close();
inReader.close();
in.close();
for (String string : list) {
String[]array= string.split(",");
try {
Stringencode= URLEncoder.encode(array[1], "UTF-8");
download(URL + encode, array[0] + ".jpg", "f://mbi2");
}catch(Exception e) {
e.printStackTrace();
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
publicstaticsynchronizedvoid download(String urlString, String filename, String savePath) throws Exception {
URLurl= newURL(urlString);
// 打开连接
HttpURLConnectioncon= (HttpURLConnection) url.openConnection();
// 设置请求超时为5s
con.setConnectTimeout(10 *1000);
// 输入流
InputStreamis = con.getInputStream();
// 1K的数据缓冲
byte[] bs = newbyte[1024];
// 读取到的数据长度
intlen;
// 输出的文件流
Filesf = new File(savePath);
if (!sf.exists()) {
sf.mkdirs();
}
OutputStreamos = new FileOutputStream(sf.getPath() + "\\" + filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
}
对于请求路径中含有中文的情况需要单独对中文经行编码
String encode = URLEncoder.encode(“中文”, "UTF-8");
一般的支持中文的编码UTF-8,GBK,GB2312,不同的浏览器用不同的编码根据以往经验谷歌UTF-8 百度GB2312 或 GBK