java实现下载功能
❶ 怎样编一个能实现文件下载功能的java程序
java实现文件下载
一、采用RequestDispatcher的方式进行
1、web.xml文件中增加
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
2、程序如下:
<%@page language="java" import="java.net.*" pageEncoding="gb2312"%>
<%
response.setContentType("application/x-download");//设置为下载application/x-download
String filenamedownload = "/系统解决方案.doc";//即将下载的文件的相对路径
String filenamedisplay = "系统解决方案.doc";//下载文件时显示的文件保存名称
filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
try
{
RequestDispatcher dispatcher = application.getRequestDispatcher(filenamedownload);
if(dispatcher != null)
{
dispatcher.forward(request,response);
}
response.flushBuffer();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
}
%>
二、采用文件流输出的方式下载
1、web.xml文件中增加
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
2、程序如下:
<%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*" pageEncoding="gb2312"%>
<%
//关于文件下载时采用文件流输出的方式处理:
//加上response.reset(),并且所有的%>后面不要换行,包括最后一个;
//因为Application Server在处理编译jsp时对于%>和<%之间的内容一般是原样输出,而且默认是PrintWriter,
//而你却要进行流输出:ServletOutputStream,这样做相当于试图在Servlet中使用两种输出机制,
//就会发生:getOutputStream() has already been called for this response的错误
//详细请见《More Java Pitfill》一书的第二部分 Web层Item 33:试图在Servlet中使用两种输出机制 270
//而且如果有换行,对于文本文件没有什么问题,但是对于其它格式,比如AutoCAD、Word、Excel等文件
//下载下来的文件中就会多出一些换行符0x0d和0x0a,这样可能导致某些格式的文件无法打开,有些也可以正常打开。
response.reset();//可以加也可以不加
response.setContentType("application/x-download");//设置为下载application/x-download
// /../../退WEB-INF/classes两级到应用的根目录下去,注意Tomcat与WebLogic下面这一句得到的路径不同,WebLogic中路径最后没有/
System.out.println(this.getClass().getClassLoader().getResource("/").getPath());
String filenamedownload = this.getClass().getClassLoader().getResource("/").getPath() + "/../../系统解决方案.doc";
String filenamedisplay = "系统解决方案.doc";//系统解决方案.txt
filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while((i = fis.read(b)) > 0)
{
output.write(b, 0, i);
}
output.flush();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(fis != null)
{
❷ 怎样使用javaweb实现上传视频和下载功能
文件上传就是将客户端资源,通过网路传递到服务器端。
因为文件数据比较大,必须通过文件上传才可以完成将数据保存到数据库端的操作。
文件上传的本质就是IO流操作。
演示:文件上传应该如何操作?
浏览器端:
1.method=post 只有post才可以携带大数据
2.必须使用<input type='file' name='f'>要有name属性
3.encType="multipart/form-data"
服务器端:
request对象是用于获取请求信息。
它有一个方法 getInputStream(); 可以获取一个字节输入流,通过这个流,可以读取到
所有的请求正文信息.
文件上传原理:
浏览器端注意上述三件事,在服务器端通过流将数据读取到,在对数据进行解析.
将上传文件内容得到,保存在服务器端,就完成了文件上传。
注意:在实际开发中,不需要我们进行数据解析,完成文件上传。因为我们会使用文件上传的工具,它们已经封装好的,提供API,只要调用它们的API就可以完成文件上传操作.我们使用的commons-fileupload,它是apache提供的一套开源免费的文件上传工具。
代码演示文件上传的原理:
在WebRoot下新建upload1.jsp
[html]view plain
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>MyJSP'index.jsp'startingpage</title>
</head>
<body>
<!--encType默认是application/x-www-form-urlencoded-->
<formaction="${pageContext.request.contextPath}/upload1"
method="POST"enctype="multipart/form-data">
<inputtype="text"name="content"><br>
<inputtype="file"name="f"><br><inputtype="submit"
value="上传">
</form>
</body>
</html>
packagecn.itcast.web.servlet;
importjava.io.IOException;
importjava.io.InputStream;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
//System.out.println("upload1servlet......");
//通过request获取一个字节输入流,将所有的请求正文信息读取到,打印到控制台
InputStreamis=request.getInputStream();
byte[]b=newbyte[1024];
intlen=-1;
while((len=is.read(b))!=-1){
System.out.println(newString(b,0,len));
}
is.close();
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doGet(request,response);
}
}
在web页面中添加上传输入项。
在Servlet中读取上传文件的数据,并保存在服务器硬盘中。
1、必须设置input输入项的name属性,否则浏览器将不会发送上传文件的数据。
2、必须把form的encType属性设为multipart/form-data 设置该值后,浏览器在上传文件时,并把文件数据附带在http请求消息体内,并使用MIME协议对上传的文件进行描述,以方便接收方对上传数据进行解析和处理。
3、表单的提交方式要设置为post。
Request对象提供了一个getInputStream方法,通过这个方法可以读取到客户端提交过来的数据。但由于用户可能会同时上传多个文件,在servlet端编程直接读取上传数据,并分别解析出相应的文件数据是一项非常麻烦的工作,示例。
为方便用户处理文件上传数据,Apache 开源组织提供了一个用来处理表单文件上传的一个开源组件( Commons-fileupload ),该组件性能优异,并且其API使用极其简单,可以让开发人员轻松实现web文件上传功能,因此在web开发中实现文件上传功能,通常使用Commons-fileupload组件实现。
使用Commons-fileupload组件实现文件上传,需要导入该组件相应支撑jar包:Commons-fileupload和commons-io。commo-io不属于文件上传组件的开发jar文件,但Commons-fileupload组件从1.1版本开始,它工作时需要commons-io包的支持。
新建Upload1Servlet 路径:/upload1
[java]view plain
在浏览器端访问信息如下:
文件上传概述
实现web开发中的文件上传功能,需要完成如下二步操作:
如何在web页面中添加上传输入项?
<input type="file">标签用于在web页面中添加文件上传输入项,设置文件上传输入项时注意:
如何在Servlet中读取文件上传数据,并保存到本地硬盘中?
❸ 手机下载功能用JAVA怎么实现
没有Java不一定就不能安装啊,Java是安装jad和jar格式的软件的
能否安装软件还取决于手机的操作系统,比如你的如果是智能手机,可以安装更高级格式的手机软件。另外,很多小牌手机,也没有Java,同样可以安装软件,那是因为他们的手机内置了类似Java的软件,可以安装与之格式符合的手机软件
❹ java 下载功能
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 = "http://www.7cd.cn/QingTengPics/倩女幽魂.mp3";//MP3下载的地址 String path ="http://img.99luna.com/music/%CF%EB%C4%E3%BE%CD%D0%B4%D0%C5.mp3"; 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下载实现
简单的方法,就是直接把你的文件做成个超链接,点击超链接的时候就可以实现下载,就能实现像你说的这种会出现保存路径,用户选择路径后,按确定,就可以下载了:
<a href="你文件的path">你的文件的名称</a> <!--文件的path可以使用相对路径-->
复杂的方法,还是使用下载组件,然后在servlet中处理
❻ java 如何实现下载功能
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 = "http://www.7cd.cn/QingTengPics/倩女幽魂.mp3";//MP3下载的地址
String path ="http://img.99luna.com/music/%CF%EB%C4%E3%BE%CD%D0%B4%D0%C5.mp3";
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桌面应用程序中实现文件下载功能吗
下载通常有本地下载(本地读取)和网络下载,两种都是通过获取数据流来实现数据的传输的。
如果是本地的文件
你可以使用FileInputStream(new File(String pathname)) 来读取pathname就是文件的完整路径名或相对路径名。
如果是网络地址,一般使用url地址作为文件的唯一地址,如果这样可以通过url的以下方法获得数据流。
openStream()
两种都是获得一个InputStream流对象,一般是读取到一个字节数组中,然后使用FileOutputStream来将字节数组输出到一个想要保存的位置。注意大文件的话需要建立缓冲区。
❽ Java文件下载怎么实现的
下载就很简单了
把你要下载的文件做成超级链接,可以不用任何组件
比如说
下载一个word文档
<a href="名称.doc">名称.doc</a>
路径你自己写
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 = "http://www.7cd.cn/QingTengPics/倩女幽魂.mp3";//MP3下载的地址
String path ="http://img.99luna.com/music/%CF%EB%C4%E3%BE%CD%D0%B4%D0%C5.mp3";
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怎样实现数据下载功能呢
这是我以前弄的一个下载的模块,里面的pl指的是System.out.println(),
详情可以看 http://magbt.com/forum.php?mod=viewthread&tid=156
package com.jc.download;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import static com.jc.tool.io.Out.pl;
public class DownloadThread extends Thread {
private String url = null;
private String file = null;
private long offset = 0;
private long length = 0;
private int no = 0;
public DownloadThread(String url, String file, long offset, long length) {
pl("正在初始化下载线程...");
this.url = url;
this.file = file;
this.offset = offset;
this.length = length;
}
public void setNo(int no) {
this.no = no;
}
@Override
public void run() {
try {
pl("线程【"+no+"】开始连接主机...");
HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection();
pl("线程【"+no+"】发送下载请求...");
conn.setRequestMethod("GET");
conn.setRequestProperty("RANGE", "bytes=" + this.offset + "-"
+ (this.offset + this.length - 1));
pl("线程【"+no+"】创建文件流...");
BufferedInputStream bis = new BufferedInputStream(
conn.getInputStream());
byte[] buf = new byte[1024];
int bytesRead;
pl("线程【"+no+"】开始向文件写入数据...");
while ((bytesRead = bis.read(buf, 0, buf.length)) != -1) {
this.writeFile(file, offset, buf, bytesRead);
this.offset += bytesRead;
}
pl("线程【"+no+"】写入完成");
} catch (IOException e) {
e.printStackTrace();
}
pl("线程【"+no+"】退出");
}
public void writeFile(String fileName, long offset, byte[] bytes,
int realLength) throws IOException {
File file = new File(fileName);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(offset);
raf.write(bytes, 0, realLength);
raf.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();
求采纳为满意回答。