java下載功能,java下載功能怎麼實現的

本文目錄一覽:

怎樣編一個能實現文件下載功能的JAVA程序

java實現文件下載

一、採用RequestDispatcher的方式進行

1、web.xml文件中增加

mime-mapping

extensiondoc/extension

mime-typeapplication/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

extensiondoc/extension

mime-typeapplication/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)

{

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 如何實現下載功能

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();

}

}

}

}

參考一下這個代碼。

java如何實現文件上傳和下載的功能

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.*;

import net.sf.json.JSONObject;

import action.StudentAction;

public class UploadServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

this.doPost(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

boolean result=true;

SmartUpload mySmartUpload=new SmartUpload();

mySmartUpload.initialize(this.getServletConfig(), request,response);

mySmartUpload.setTotalMaxFileSize(50*1024*1024);//大小限制

mySmartUpload.setAllowedFilesList(“doc,docx”);//後綴名限制

try {

mySmartUpload.upload();

com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);

myFile.saveAs(“/file/”+1+”.doc”);//保存目錄

} catch (SmartUploadException e) {

e.printStackTrace();result=false;

}

//*****************************//

response.setContentType(“text/html;charset=UTF-8”);

response.setHeader(“Cache-Control”,”no-cache”);

PrintWriter out = response.getWriter();

out.print(result);

out.flush();

out.close();

}

}

//我這是ajax方式的,不想這樣,把//**********************//以下部分修改就行了

//需要SmartUpload組件,去網上下個就行了,也有介紹的

Java如何利用url下載MP3保存到本地?

Java如何利用url下載MP3保存的方法:

1 /** ;

2      * TODO 下載文件到本地 ;

3      * @author nadim  ;

4      * @date Sep 11, 2015 11:45:31 AM ;

5      * @param fileUrl 遠程地址 ;

6      * @param fileLocal 本地路徑 ;

7      * @throws Exception ;

8      */ ;

9     public void downloadFile(String fileUrl,String fileLocal) throws Exception {;

10         URL url = new URL(fileUrl);

11         HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();

12         urlCon.setConnectTimeout(6000);

13         urlCon.setReadTimeout(6000);

14         int code = urlCon.getResponseCode();

15         if (code != HttpURLConnection.HTTP_OK) {

16             throw new Exception(“文件讀取失敗”);

17         }      

18         //讀文件流;

19        DataInputStream in = new DataInputStream(urlCon.getInputStream());

20         DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));

21         byte[] buffer = new byte[2048];

22         int count = 0;

23         while ((count = in.read(buffer)) 0) {;

24             out.write(buffer, 0, count);

25         }

26         out.close();

27         in.close();

28     }。

Java是一門面向對象編程語言,不僅吸收了C++語言的各種優點,還摒棄了C++里難以理解的多繼承、指針等概念,因此Java語言具有功能強大和簡單易用兩個特徵。

Java語言作為靜態面向對象編程語言的代表,極好地實現了面向對象理論,允許程序員以優雅的思維方式進行複雜的編程 。

java怎樣實現數據下載功能呢

這是我以前弄的一個下載的模塊,裡面的pl指的是System.out.println(),

詳情可以看 ;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();

}

}

原創文章,作者:PTMWJ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/325604.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
PTMWJ的頭像PTMWJ
上一篇 2025-01-13 13:24
下一篇 2025-01-13 13:24

相關推薦

  • Java JsonPath 效率優化指南

    本篇文章將深入探討Java JsonPath的效率問題,並提供一些優化方案。 一、JsonPath 簡介 JsonPath是一個可用於從JSON數據中獲取信息的庫。它提供了一種DS…

    編程 2025-04-29
  • java client.getacsresponse 編譯報錯解決方法

    java client.getacsresponse 編譯報錯是Java編程過程中常見的錯誤,常見的原因是代碼的語法錯誤、類庫依賴問題和編譯環境的配置問題。下面將從多個方面進行分析…

    編程 2025-04-29
  • Java Bean載入過程

    Java Bean載入過程涉及到類載入器、反射機制和Java虛擬機的執行過程。在本文中,將從這三個方面詳細闡述Java Bean載入的過程。 一、類載入器 類載入器是Java虛擬機…

    編程 2025-04-29
  • Java騰訊雲音視頻對接

    本文旨在從多個方面詳細闡述Java騰訊雲音視頻對接,提供完整的代碼示例。 一、騰訊雲音視頻介紹 騰訊雲音視頻服務(Cloud Tencent Real-Time Communica…

    編程 2025-04-29
  • Java Milvus SearchParam withoutFields用法介紹

    本文將詳細介紹Java Milvus SearchParam withoutFields的相關知識和用法。 一、什麼是Java Milvus SearchParam without…

    編程 2025-04-29
  • Java 8中某一周的周一

    Java 8是Java語言中的一個版本,於2014年3月18日發布。本文將從多個方面對Java 8中某一周的周一進行詳細的闡述。 一、數組處理 Java 8新特性之一是Stream…

    編程 2025-04-29
  • Java判斷字元串是否存在多個

    本文將從以下幾個方面詳細闡述如何使用Java判斷一個字元串中是否存在多個指定字元: 一、字元串遍歷 字元串是Java編程中非常重要的一種數據類型。要判斷字元串中是否存在多個指定字元…

    編程 2025-04-29
  • VSCode為什麼無法運行Java

    解答:VSCode無法運行Java是因為默認情況下,VSCode並沒有集成Java運行環境,需要手動添加Java運行環境或安裝相關插件才能實現Java代碼的編寫、調試和運行。 一、…

    編程 2025-04-29
  • Java任務下發回滾系統的設計與實現

    本文將介紹一個Java任務下發回滾系統的設計與實現。該系統可以用於執行複雜的任務,包括可回滾的任務,及時恢復任務失敗前的狀態。系統使用Java語言進行開發,可以支持多種類型的任務。…

    編程 2025-04-29
  • Java 8 Group By 會影響排序嗎?

    是的,Java 8中的Group By會對排序產生影響。本文將從多個方面探討Group By對排序的影響。 一、Group By的概述 Group By是SQL中的一種常見操作,它…

    編程 2025-04-29

發表回復

登錄後才能評論