重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
你的这段代码有两处让人疑惑。其一、File()这个构造函数,自已查下API
公司主营业务:成都网站设计、成都做网站、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联公司是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联公司推出鸡冠免费做网站回馈大家。
其二、FileOutputStream,FileOutputStream(String name)创建一个向具有指定名称的文件中写入数据的输出文件流。它只是创建了一个输出流,其中没有具体的值,那么这个值来自哪呢,其就来自于你的输入流。其中FileOutputStream()中只是创建了一个字节输出流,其只能接受字节流的输出,所以它还需要与DataOutputStream()的配合才能完成输出,具体用法你可以查API
在jsp/servlet中断点/多线程下载文件
%@ page import="java.io.File" %%@ page import="java.io.IOException" %%@ page import="java.io.OutputStream" %%@ page import="java.io.RandomAccessFile" %%! public void downloadFile(HttpServletRequest request, HttpServletResponse response, File file) throws IOException { RandomAccessFile raf = new RandomAccessFile(file, "r"); java.io.FileInputStream fis = new java.io.FileInputStream(raf.getFD()); response.setHeader("Server", ""); response.setHeader("Accept-Ranges", "bytes"); long pos = 0; long len; len = raf.length(); if (request.getHeader("Range") != null) { response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); pos = Long.parseLong(request.getHeader("Range") .replaceAll("bytes=", "") .replaceAll("-", "") ); } response.setHeader("Content-Length", Long.toString(len - pos)); if (pos != 0) { response.setHeader("Content-Range", new StringBuffer() .append("bytes ") .append(pos) .append("-") .append(Long.toString(len - 1)) .append("/") .append(len) .toString() ); } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", new StringBuffer() .append("attachment;filename=\"") .append(file.getName()) .append("\"").toString()); raf.seek(pos); byte[] b = new byte[2048]; int i; OutputStream outs = response.getOutputStream(); while ((i = raf.read(b)) != -1) { outs.write(b, 0, i); } raf.close(); fis.close(); }%% String filePath = request.getParameter("file"); filePath = application.getRealPath(filePath); File file = new File(filePath); downloadFile(request, response, file);%
是否可以解决您的问题?
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(); } } }}
参考一下这个代码。
利用struts2的上传下载
package com.java.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileAction extends ActionSupport {
/**
* 用于上传的变量
*/
//封装该文件域对应的文件内容
private File[] upload;
//封装该文件域对应的文件的文件名
private String[] uploadFileName;
//封装该文件域对应的文件的文件类型
private String[] uploadContentType;
/**
* 用于下载的变量
*/
private String[] fileNames;
private String fileName;
/**
* 设置getter和setter
* @return
*/
public String[] getFileNames() {
return fileNames;
}
public File[] getUpload() {
return upload;
}
public void setUpload(File[] upload) {
this.upload = upload;
}
public String[] getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String[] getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setFileNames(String[] fileNames) {
this.fileNames = fileNames;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* 用于上传文件的方法
* @return
*/
public String upload(){
//设置文件上传到的位置
String path = ServletActionContext.getServletContext().getRealPath("/file");
//设置文件目标
try {
for (int i = 0; i upload.length; i++) {
File target = new File(path, uploadFileName[i]);
FileUtils.copyFile(upload[i], target);
}
return SUCCESS;
} catch (IOException e) {
e.printStackTrace();
}
return INPUT;
}
/**
* 得到所有上传的文件的名称
* @return
*/
public String fileList(){
String path = ServletActionContext.getServletContext().getRealPath("/file");
fileNames = new File(path).list();
return SUCCESS;
}
/**
* 用于下载文件的方法
* @return
*/
public InputStream getInputStream(){
if(fileName==null || fileName.isEmpty()) return null;
String path = ServletActionContext.getServletContext().getRealPath("/file");
try {
return new FileInputStream(new File(path,fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public String getContentDisposition(){
try {
if(fileName==null||fileName.isEmpty()){
return "inline";
}
return "attachment;filename="+URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "inline";
}
}
比java的io方便多了