java实现下载功能代码,java实现下载功能代码的方法
java 如何实现下载功能
import java.io.File;
方山网站制作公司哪家好,找成都创新互联!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设公司等网站项目制作,到程序开发,运营维护。成都创新互联于2013年创立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选成都创新互联。
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();
}
}
}
}
参考一下这个代码。
通过java实现文件下载
在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);%
是否可以解决您的问题?
用java语言编写一个下载程序
package com.etc.week6.day04; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.net.UnknownHostException; /** * socket 8801 * 各种流..... * 线程... * 1: 请选择需要下载文件: * 2:文件的标记 * 3: 正在下载.... * 4: 接受服务器文件内容 * 写入指定目录下.... */ public class DownloadClient { public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException { new DownloadClient().startup(); } private String desRoot="demo/pp/"; public void startup() throws UnknownHostException, IOException, InterruptedException{ System.out.println("client:"); Socket s= new Socket("localhost",5555); DataInputStream dis= new DataInputStream(s.getInputStream()); DataOutputStream dos= new DataOutputStream(s.getOutputStream()); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // 1: String fileList = dis.readUTF(); System.out.println("选择下载的文件的标号...."); System.out.println(fileList); // 2 控制台输入的文件标号 String fileNum = br.readLine(); dos.writeUTF(fileNum); System.out.println("正在下载......"); Thread.sleep(3000); // 3 获取服务端传过来的文件名 进行下载 String fileName = dis.readUTF(); // 获取服务端传过来的文件名.... // 4: 指定到目标目录下..... File file =new File(desRoot,fileName); BufferedOutputStream bos= new BufferedOutputStream( new FileOutputStream(file)); int b=-1; while((b=dis.read())!=-1){ bos.write(b); } bos.close(); System.out.println("文件下载结束"); if(s!=null){ s.close(); } } }
java下载功能实现
楼主得在后台的控制器中用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();
求采纳为满意回答。
java 下载功能
下载功能实际上就是将远程服务器的文件流通过ftp功能转换为本地文件流进行存储。举例:
/**
*下载并解压文件
*
* @param localFilePath
* @param fileName
* @param routeFilepath
* @return
* @throws Exception
*/
public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FileOutputStream fos = null;
FTPClient ftpClient = new FTPClient();
String SFP = System.getProperty("file.separator");
String bl = "false";
try {
Log.info("下载并解密文件开始");
Log.info("连接远程下载服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
FTPFile[] fs;
ftpClient.makeDirectory(routeFilepath);
ftpClient.changeWorkingDirectory(routeFilepath);
bl = "false";
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
bl = "true";
Log.info("下载文件开始。");
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
InputStream is = ftpClient.retrieveFileStream(fileName);
bos = new ByteArrayOutputStream(is.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
fos = new FileOutputStream(localFilePath+SFP+fileName);
fos.write(bos.toByteArray());
Log.info("下载文件结束:"+localFilePath);
}
}
Log.info("检查文件是否存:"+fileName+" "+bl);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon("查询无结果,请稍后再查询。");
return bl;
}
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
备注:只需要修改 ftpClient.connect方法中的用户名和密码即可进行远程服务器连接下载,具体的根据实际情况修改即可。
java 实现下载
首先有2种方法:
1. 用超链接标签直接链接至文件路径,前提是这个文件在项目系统的相对路径下;
2. 利用java代码实现,先读取文件,然后以流的形式发送到浏览器;这种方法就是不管文件在操作系统的什么地方都可以读取;而且还可以重写客户接受的文件的名称。
类似的代码你上网查查就可以了,很多的
文章标题:java实现下载功能代码,java实现下载功能代码的方法
URL链接:http://azwzsj.com/article/dsijihs.html