您的位置:首页 > 编程语言 > Java开发

java实现网上下载文件到本地

2015-11-28 13:54 525 查看
思路:

要弄清网上下载文件的一些关键逻辑。我们要从网上获取信息,第一步必须要有网络连接(connection),接着是你要获取信息的路径(ResourceUrl),然后你要对获取到的信息的处理(process),而在这里我们对信息的处理是“下载文件到本地”,下载要确定好保存位置(SavePath)。

由此,我们可以得到的简单的思维顺序是:建立连接——>得到源url——>确定保存位置。于是有下面的基本步骤。

基本步骤:

1.建立http连接,获取连接对象

2.输入流读取文件

3.建立存储的目录、保存的文件名

4.输出流写数据

5.关闭流

主要方法:

/**
* 网上获取文件
*
* @param savepath 保存路径
* @param resurl  资源路径
* @param fileName  自定义资源名
*/
public void getInternetRes(String savepath, String resurl, String fileName) {
URL url = null;
HttpURLConnection con = null;
InputStream in = null;
FileOutputStream out = null;
try {
url = new URL(resurl);
//建立http连接,得到连接对象
con = (HttpURLConnection) url.openConnection();
//con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
in = con.getInputStream();
byte[] data = getByteData(in);//转化为byte数组

File file = new File(savepath);
if (!file.exists()) {
file.mkdirs();
}

File res = new File(file + File.separator + fileName);
out = new FileOutputStream(res);
out.write(data);
System.out.println("downloaded successfully!");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != out)
out.close();
if (null != in)
in.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}


/**
* 从输入流中获取字节数组
*
* @param in
* @return
* @throws IOException
*/
private byte[] getByteData(InputStream in) throws IOException {
byte[] b = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(b)) != -1) {
bos.write(b, 0, len);
}
if(null!=bos){
bos.close();
}
return bos.toByteArray();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  IO操作 java