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();
求採納為滿意回答。