现在的位置: 首页 > 综合 > 正文

java常用代码四(粘贴即用)—下载文件

2018年04月10日 ⁄ 综合 ⁄ 共 900字 ⁄ 字号 评论关闭

本文给出java下载文件的常用代码,代码适用于windows和linux,会持续更新。

java下载文件:

所需头文件:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

代码部分:

/**
	 * 从指定文件的url下载文件
	 * @param url 指定文件的url
	 * @param filename 下载后存储的位置
	 * @throws IOException
	 */
	public void fetchFile(String url,String filename) throws IOException
	{
		//建立一个到需要下载文件的URL的http链接
		URL _URL=new URL(url);
		HttpURLConnection con=(HttpURLConnection) _URL.openConnection();
		
		InputStream is=con.getInputStream();
		
		//新建一个文件作为下载后的文件
		File downloadfile=new File(filename);
		FileOutputStream fos=new FileOutputStream(downloadfile);
		
		//将从http链接中获取的网络流读取的数据直接写入文件流
		byte[] buf=new byte[1000];
		int read;
		while((read=is.read(buf))!=-1)
		{
			fos.write(buf,0,read);
		}
		is.close();
		fos.close();
	}

使用示例:

public static void main(String[] args) throws IOException
	{
		new FileFetcher().fetchFile("http://image.s1979.com/allimg/120712/15361I934-4.jpg","download.jpg");
	}

抱歉!评论已关闭.