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");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM