您的位置:首页 > 理论基础 > 计算机网络

java 从网络Url中下载文件

2016-12-22 18:29 567 查看
参考文章:
http://blog.csdn.net/xb12369/article/details/40543649/ http://www.runoob.com/java/java-url-processing.html
有时候我们需要从网络或者资源服务器等外部非本地环境下载文件,这就需要我们通过URL来访问地址。

URL(Uniform Resource Locator)中文名为统一资源定位符,有时也被俗称为网页地址。表示为互联网上的资源,如网页或者FTP地址。

java.net.URL提供了丰富的URL构建方式,并可以通过java.net.URL来获取资源。

序号方法描述
1public URL(String protocol, String host, int port, String file) throws MalformedURLException.

通过给定的参数(协议、主机名、端口号、文件名)创建URL。
2public URL(String protocol, String host, String file) throws MalformedURLException

使用指定的协议、主机名、文件名创建URL,端口使用协议的默认端口。
3public URL(String url) throws MalformedURLException

通过给定的URL字符串创建URL
4public URL(URL context, String url) throws MalformedURLException

使用基地址和相对URL创建
URL类中包含了很多方法用于访问URL的各个部分,具体方法及描述如下:

序号方法描述
1public String getPath()

返回URL路径部分。
2public String getQuery()

返回URL查询部分。
3public String getAuthority()

获取此 URL 的授权部分。
4public int getPort()

返回URL端口部分
5public int getDefaultPort()

返回协议的默认端口号。
6public String getProtocol()

返回URL的协议
7public String getHost()

返回URL的主机
8public String getFile()

返回URL文件名部分
9public String getRef()

获取此 URL 的锚点(也称为"引用")。
10public URLConnection openConnection() throws IOException

打开一个URL连接,并运行客户端访问资源。
URLConnections 类方法

openConnection() 返回一个 java.net.URLConnection。

例如:

如果你连接HTTP协议的URL, openConnection() 方法返回 HttpURLConnection 对象。

如果你连接的URL为一个 JAR 文件, openConnection() 方法将返回 JarURLConnection 对象。

等等...

URLConnection 方法列表如下:

序号方法描述
1Object getContent() 

检索URL链接内容
2Object getContent(Class[] classes) 

检索URL链接内容
3String getContentEncoding() 

返回头部 content-encoding 字段值。
4int getContentLength() 

返回头部 content-length字段值
5String getContentType() 

返回头部 content-type 字段值
6int getLastModified() 

返回头部 last-modified 字段值。
7long getExpiration() 

返回头部 expires 字段值。
8long getIfModifiedSince() 

返回对象的 ifModifiedSince 字段值。
9public void setDoInput(boolean input)

URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 true。
10public void setDoOutput(boolean output)

URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false。
11public InputStream getInputStream() throws IOException

返回URL的输入流,用于读取资源
12public OutputStream getOutputStream() throws IOException

返回URL的输出流, 用于写入资源。
13public URL getURL()

返回 URLConnection 对象连接的URL
下面是URL的工具方法,我们在downLoadFromUrl添加url地址,文件名称(自定义)和文件下载路径就可以在获取网页或者FTP上的文件。

建议:文件名,文件路径不要使用中文

/**
* 从网络Url中下载文件
* @param urlStr
* @param fileName
* @param savePath
* @throws IOException
*/
public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);

//文件保存位置
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+File.separator+fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if(fos!=null){
fos.close();
}
if(inputStream!=null){
inputStream.close();
}

System.out.println("info:"+url+" download success");

}

/**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
public static  byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}

public static void main(String[] args) {
try{
downLoadFromUrl("http://101.95.48.97:8005/res/upload/interface/apptutorials/manualstypeico/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png",
"baidu.jpg","D:/");
}catch (Exception e) {
// TODO: handle exception
}
}

记录一下这个:

File file = new File(path);// path是根据日志路径和文件名拼接出来的
String filename = file.getName();// 获取日志文件名称
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
os.write(buffer);// 输出文件
os.flush();
os.close();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: