java根据地址(链接)下载⽂件到本地package smon.util;
//An highlighted block
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.HttpURLConnection;
import java.MalformedURLException;
import java.URL;
import java.URLConnection;
import java.URLDecoder;
ParseException;
SimpleDateFormat;
import java.util.Random;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Caiji {
// public static void main(String[] args) throws UnsupportedEncodingException
/
/ {
//
// String photoUrl = "XXXXXXXXXXXXXXX.pdf";
// //
//
// String fileName = photoUrl.substring(photoUrl.lastIndexOf("/")); //为下载的⽂件命名
// fileName = URLDecoder.decode(fileName,"utf-8");
// String filePath = "D:/caiji/"+fileName+"/"; //保存⽬录
//
// File file = saveUrlAs(photoUrl, filePath ,"GET");
// }
/
**
* ⽣成6位随机字符串
* @return
*/
public static String getRandomStr() {
int length = 6;
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = Int(base.length());
sb.append(base.charAt(number));
}
String();
}
public static File saveUrlAs(String url,String filePath,String method){
//System.out.println("fileName---->"+filePath);
//创建不同的⽂件夹⽬录
File file=new File(filePath);
//判断⽂件夹是否存在
if (!ists())
{
/
/如果⽂件夹不存在,则创建新的的⽂件夹
file.mkdirs();
}
FileOutputStream fileOut = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try
{
// 建⽴链接
URL httpUrl=new URL(url);
conn=(HttpURLConnection) httpUrl.openConnection();
/
/以Post⽅式提交表单,默认get⽅式
conn.setRequestMethod(method);
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); conn.setDoInput(true);
conn.setDoOutput(true);
// post⽅式不能使⽤缓存
conn.setUseCaches(false);
//连接指定的资源
//获取⽹络输⼊流
InputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
//判断⽂件的保存路径后⾯是否以/结尾
// if (!dsWith("/")) {
//
// filePath += "/";
//
// }
//写⼊到⽂件(注意⽂件保存路径的后⾯⼀定要加上⽂件的名称)
fileOut = new FileOutputStream(filePath+getRandomStr()+".pdf");
BufferedOutputStream bos = new BufferedOutputStream(fileOut);
byte[] buf = new byte[4096];
int length = ad(buf);
connect下载/
/保存⽂件
while(length != -1)
{
bos.write(buf, 0, length);
length = ad(buf);
}
bos.close();
bis.close();
conn.disconnect();
} catch (Exception e)
{
e.printStackTrace();
System.out.println("抛出异常!!");
}
return file;
}
}