FileUtils (从磁盘下载,从网络下载)

Posted duanqiao123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FileUtils (从磁盘下载,从网络下载)相关的知识,希望对你有一定的参考价值。

public class FileUtils {

/**
* realPath 磁盘路径 D://project/download/
* urlPath 后半部分路径 具体根据业务需求,例如:WEB-INF/download.xlsx
* downLoadName 下载后的新名字
* @param request
* @param resp
*/
public static void downloadFromDisk(HttpServletRequest request, HttpServletResponse resp,String realPath,String urlPath,String downLoadName) {
//文件最终路径,例如:D://project/download/WEB-INF/download.xlsx
String path = realPath + File.separator + urlPath;
File file = new File(path);
if(!file.exists()){
System.out.println("---------<系统找不到指定的文件>---------");
return;
}
resp.reset();
resp.setContentType("application/octet-stream");
resp.setCharacterEncoding("utf-8");
resp.setContentLength((int) file.length());
//下载到本地的文件名,例如:abc.xlsx(注意:这里跟路径中的文件名区分开)
String downloadName = downLoadName;
resp.setHeader("Content-Disposition", "attachment;filename=" + downloadName );
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = resp.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
System.out.println("---------<文件下载成功>---------");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void downloadFromIntNet(String urlStr, String fileName, String savePath) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为5秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//创建保存路径
File saveDir = new File(savePath);
if(!saveDir.exists()) {
saveDir.mkdir();
}
//创建文件
File file = new File(saveDir+File.separator+fileName);
//文件输出流
FileOutputStream fout = new FileOutputStream(file);
//输出文件
byte[] buff = new byte[4096];
int len = -1;
while ((len = inputStream.read(buff)) != -1) {
fout.write(buff,0,len);
}
//关闭输出输入流
fout.close();
inputStream.close();
System.out.println("info:"+url+" download success");
}

}


----------------------------------调用---------------------------------------
/*从磁盘下载*/
String realPath = "C:\files\images";
String urlPath = "user.png";
String downLoadName = "newname.png";
FileUtils.downloadFromDisk(request,resp,realPath,urlPath,downLoadName);
/*从网络下载*/
String path = "http://yourIP:yourPort/files/201111/images/2019/12/24/2019122409504998593372629015.jpg";
FileUtils.downloadFromIntNet(path,"test.jpg","C:\myfile\images");

以上是关于FileUtils (从磁盘下载,从网络下载)的主要内容,如果未能解决你的问题,请参考以下文章

HttpClient请求服务器图片

从 URL 下载返回的 Zip 文件

使 wget 从 bash 直接下载文件到磁盘

小牛加速器需要用到的权限

linux如何从远程终端下载文件到本地磁盘?

linux 如何从远程终端下载文件到本地磁盘? 我的系统也是linux的,想从远程终端(ssh.)上复制文件到本地