下载远程url文件(或者文件流)到本地
2013-05-10 10:12
246 查看
这里的remoteFilePath 为远程文件,可理解为就是一个文件地址(实际可能为返回的文件流)
/**
* 获取远程文件
* @param remoteFilePath 远程文件路径
* @param localFilePath 本地文件路径
*/
public void downloadFile(String remoteFilePath, String localFilePath)
{
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String fileName = "mcsetup.exe";
String ramdom = System.currentTimeMillis() + ""
+ new Random().nextInt(100) + new Random().nextInt(100)
+ new Random().nextInt(100) + getSequence();
fileName = ramdom + "_" + fileName;
File f = new File(localFilePath+fileName);
try
{
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection)urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(f));
int len = 2048;
byte[] b = new byte[len];
while ((len = bis.read(b)) != -1)
{
bos.write(b, 0, len);
}
bos.flush();
bis.close();
httpUrl.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
bis.close();
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* 获取远程文件
* @param remoteFilePath 远程文件路径
* @param localFilePath 本地文件路径
*/
public void downloadFile(String remoteFilePath, String localFilePath)
{
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String fileName = "mcsetup.exe";
String ramdom = System.currentTimeMillis() + ""
+ new Random().nextInt(100) + new Random().nextInt(100)
+ new Random().nextInt(100) + getSequence();
fileName = ramdom + "_" + fileName;
File f = new File(localFilePath+fileName);
try
{
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection)urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(f));
int len = 2048;
byte[] b = new byte[len];
while ((len = bis.read(b)) != -1)
{
bos.write(b, 0, len);
}
bos.flush();
bis.close();
httpUrl.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
bis.close();
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
相关文章推荐
- ASP.NET获取远程网页下载到本地文件,通过URL生成静态文件的做法
- 利用HttpURLConnection实现远程下载文件
- PHP下载远程文件到本地存储的方法
- Android从远程服务器下载文件到本地sd卡中
- C#访问远程服务器共享目录下载文件到本地
- Android WebView使用实例(html5、文件下载和远程URL)
- 如何使用git命令将远程仓库项目下载到本地文件
- QTP 通过URL地址下载文件到本地
- 自动将远程页面的文件中的图片下载到本地服务器
- 用js实现下载远程文件并保存在本地的脚本
- PHP通过url下载远程图片到本地
- 【转载】使用jsp实现文件上传到服务器或者从服务器上下载文件到本地计算机完整说明版
- java网络编程____使用url下载远程文件(图片,软件等)
- PHP代码实现远程下载文件到本地的函数
- PHP实现远程下载文件到本地
- 针对从远程服务器下载大文件到本地
- 批处理完成FTP下载远程备份文件到本地
- PHP 判断远程或者本地文件是否存在
- PHP CURL实现远程下载文件到本地
- 读取文件中的URL,下载到本地,删除原文件