java 根据地址(链接)下载文件到本地

package com.sinosoft.cms.common.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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.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 = "http://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 = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static File saveUrlAs(String url,String filePath,String method){
//System.out.println("fileName---->"+filePath);
//创建不同的文件夹目录
File file=new File(filePath);
//判断文件夹是否存在
if (!file.exists())
{
//如果文件夹不存在,则创建新的的文件夹
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);
//连接指定的资源
conn.connect();
//获取网络输入流
inputStream=conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
//判断文件的保存路径后面是否以/结尾
// if (!filePath.endsWith("/")) {
//
// filePath += "/";
//
// }
//写入到文件(注意文件保存路径的后面一定要加上文件的名称)
fileOut = new FileOutputStream(filePath+getRandomStr()+".pdf");
BufferedOutputStream bos = new BufferedOutputStream(fileOut);

byte[] buf = new byte[4096];
int length = bis.read(buf);
//保存文件
while(length != -1)
{
bos.write(buf, 0, length);
length = bis.read(buf);
}
bos.close();
bis.close();
conn.disconnect();
} catch (Exception e)
{
e.printStackTrace();
System.out.println("抛出异常!!");
}

return file;

}

 

}

posted on 2020-05-20 17:22  多言  阅读(12019)  评论(1编辑  收藏  举报

导航