import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.ProtocolException;import java.net.URI;import java.net.URL;import java.util.Random;/** * * 實(shí)現(xiàn)了下載的功能*/ public class SimpleTh { public static void main(String[] args){ // TODO Auto-generated method stub //String path = "倩女幽魂.mp3";//MP3下載的地址 String path =""; try { new SimpleTh().download(path, 3); //對象調(diào)用下載的方法 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static String getFilename(String path){//獲得文件的名字 return path.substring(path.lastIndexOf('/')+1); } public void download(String path,int threadsize) throws Exception//下載的方法 {//參數(shù) 下載地址,線程數(shù)量 URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection();//獲取HttpURLConnection對象 conn.setRequestMethod("GET");//設(shè)置請求格式,這里是GET格式 conn.setReadTimeout(5*1000);// int filelength = conn.getContentLength();//獲取要下載文件的長度 String filename = getFilename(path); File saveFile = new File(filename); RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd"); accessFile.setLength(filelength); accessFile.close(); int block = filelength%threadsize ==0?filelength/threadsize:filelength/threadsize+1; for(int threadid = 0;threadid=threadsize;threadid++){ new DownloadThread(url,saveFile,block,threadid).start(); } } private final class DownloadThread extends Thread{ private URL url; private File saveFile; private int block;//每條線程下載的長度 private int threadid;//線程id public DownloadThread(URL url,File saveFile,int block,int threadid){ this.url = url; this.saveFile= saveFile; this.block = block; this.threadid = threadid; } @Override public void run() { //計(jì)算開始位置的公式:線程id*每條線程下載的數(shù)據(jù)長度=? //計(jì)算結(jié)束位置的公式:(線程id+1)*每條線程下載數(shù)據(jù)長度-1=? int startposition = threadid*block; int endposition = (threadid+1)*block-1; try { try { RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd"); accessFile.seek(startposition);//設(shè)置從什么位置寫入數(shù)據(jù) HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5*1000); conn.setRequestProperty("Range","bytes= "+startposition+"-"+endposition); InputStream inStream = conn.getInputStream(); byte[]buffer = new byte[1024]; int len = 0; while((len = inStream.read(buffer))!=-1){ accessFile.write(buffer, 0, len); } inStream.close(); accessFile.close(); System.out.println("線程id:"+threadid+"下載完成"); } catch (FileNotFoundException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } }}
讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來自于我們對這個(gè)行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長期合作伙伴,公司提供的服務(wù)項(xiàng)目有:域名注冊、雅安服務(wù)器托管、營銷軟件、網(wǎng)站建設(shè)、秭歸網(wǎng)站維護(hù)、網(wǎng)站推廣。
參考一下這個(gè)代碼。
private File uploadify;
private String uploadifyFileName;
public String uploadFile1() throws Exception {
String extName = "";// 擴(kuò)展名
String newFileName = "";// 新文件名
String nowTime = df.format(new Date());// 當(dāng)前時(shí)間
String random = "-" + (Math.round(Math.random() * 9000) + 1000);// 隨機(jī)函數(shù)
String path = "uploads/" + nowTime.substring(0, 6) + "/"
+ nowTime.substring(0, 8) + "/";// 保存路徑
String savePath = ServletActionContext.getServletContext().getRealPath(
"");
savePath = savePath.replace("\\", "/");
if (!savePath.substring(savePath.length()).equals("/"))
savePath = savePath + "/";
savePath = savePath + path;
// 獲取擴(kuò)展名
if (uploadifyFileName.lastIndexOf(".") = 0) {
extName = uploadifyFileName.substring(uploadifyFileName
.lastIndexOf("."));
}
newFileName = uploadifyFileName.substring(0,
uploadifyFileName.lastIndexOf("."))
+ nowTime.substring(8) + random + extName;
File file = new File(savePath);
if (!file.exists())
file.mkdirs();
uploadify.renameTo(new File(savePath + newFileName));
/*
* HttpServletResponse response = ServletActionContext.getResponse();
* response.setCharacterEncoding("utf-8");
* response.getWriter().print(uploadifyFileName+"上傳成功");
*/
String ctx = Struts2Utils.getRequest().getContextPath();
Struts2Utils.renderText(ctx + "/" + path + newFileName);
Wenjdetail detail = new Wenjdetail();
String pt = path + newFileName;
detail.setName(uploadifyFileName);
detail.setUrl(pt);
wenjdetailManager.saveWenjdetail(detail);
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
response.getWriter().print("," + detail.getId());
return null; // 這里不需要頁面轉(zhuǎn)向,所以返回空就可以了
}
樓主得在后臺(tái)的控制器中用reponse的輸出流轉(zhuǎn)化一下,我給你個(gè)例子。
InputStream?fis?=?new?BufferedInputStream(new?FileInputStream(filePath));
byte[]?buffer?=?new?byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader("Content-Disposition",?"attachment;filename="?+?new?String(fileName.getBytes("gbk"),"ISO-8859-1"));
response.addHeader("Content-Length",?""?+?excelFile.length());
OutputStream?toClient?=?new?BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
下載代碼:
這里我使用的是SpringMVC,不過它在這里的唯一用途就是用來獲取ServletContext對象,這個(gè)對象的用途,下面實(shí)例中有說明
下載,需要用到兩個(gè)jar包:commons-fileupload.jar和commons-io.jar
Java代碼
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@Controller
public class FileController implements ServletContextAware{
//Spring這里是通過實(shí)現(xiàn)ServletContextAware接口來注入ServletContext對象
private ServletContext servletContext;
@RequestMapping("file/download")
public void fileDownload(HttpServletResponse response){
//獲取網(wǎng)站部署路徑(通過ServletContext對象),用于確定下載文件位置,從而實(shí)現(xiàn)下載
String path = servletContext.getRealPath("/");
//1.設(shè)置文件ContentType類型,這樣設(shè)置,會(huì)自動(dòng)判斷下載文件類型
response.setContentType("multipart/form-data");
//2.設(shè)置文件頭:最后一個(gè)參數(shù)是設(shè)置下載文件名(假如我們叫a.pdf)
response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf");
ServletOutputStream out;
//通過文件路徑獲得File對象(假如此路徑中有一個(gè)download.pdf文件)
File file = new File(path + "download/" + "download.pdf");
try {
FileInputStream inputStream = new FileInputStream(file);
//3.通過response獲取ServletOutputStream對象(out)
out = response.getOutputStream();
int b = 0;
byte[] buffer = new byte[512];
while (b != -1){
b = inputStream.read(buffer);
//4.寫到輸出流(out)中
out.write(buffer,0,b);
}
inputStream.close();
out.close();
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
}
本文名稱:java下載功能代碼,java 下載功能
網(wǎng)頁地址:http://chinadenli.net/article42/dseooec.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標(biāo)簽優(yōu)化、網(wǎng)站維護(hù)、網(wǎng)站建設(shè)、響應(yīng)式網(wǎng)站、品牌網(wǎng)站建設(shè)、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)