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;/** * * 实现了下载的功能*/ 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); //对象调用下载的方法 } 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//下载的方法 {//参数 下载地址,线程数量 URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection();//获取HttpURLConnection对象 conn.setRequestMethod("GET");//设置请求格式,这里是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() { //计算开始位置的公式:线程id*每条线程下载的数据长度=? //计算结束位置的公式:(线程id+1)*每条线程下载数据长度-1=? int startposition = threadid*block; int endposition = (threadid+1)*block-1; try { try { RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd"); accessFile.seek(startposition);//设置从什么位置写入数据 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(); } } }}
让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:域名注册、雅安服务器托管、营销软件、网站建设、秭归网站维护、网站推广。
参考一下这个代码。
private File uploadify;
private String uploadifyFileName;
public String uploadFile1() throws Exception {
String extName = "";// 扩展名
String newFileName = "";// 新文件名
String nowTime = df.format(new Date());// 当前时间
String random = "-" + (Math.round(Math.random() * 9000) + 1000);// 随机函数
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;
// 获取扩展名
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; // 这里不需要页面转向,所以返回空就可以了
}
楼主得在后台的控制器中用reponse的输出流转化一下,我给你个例子。
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对象,这个对象的用途,下面实例中有说明
下载,需要用到两个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这里是通过实现ServletContextAware接口来注入ServletContext对象
private ServletContext servletContext;
@RequestMapping("file/download")
public void fileDownload(HttpServletResponse response){
//获取网站部署路径(通过ServletContext对象),用于确定下载文件位置,从而实现下载
String path = servletContext.getRealPath("/");
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
//2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)
response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf");
ServletOutputStream out;
//通过文件路径获得File对象(假如此路径中有一个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;
}
}