java下載文件的代碼,java下載文件的代碼是多少

通過(guò)java實(shí)現(xiàn)文件下載

在jsp/servlet中斷點(diǎn)/多線程下載文件

竹溪網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)建站,竹溪網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為竹溪成百上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)營(yíng)銷(xiāo)網(wǎng)站建設(shè)要多少錢(qián),請(qǐng)找那個(gè)售后服務(wù)好的竹溪做網(wǎng)站的公司定做!

%@ 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);%

是否可以解決您的問(wèn)題?

java 文件上傳下載的代碼

FileInputStream fin = new FileInputStream(new File("你的文件地址"));

OutputStream out = 你的目標(biāo)流地址,可以是Socket的Output流,也可以是http的Output流,等等

byte[] b = new byte[65535]; // 一次讀取多少字節(jié)

int read = -1;

while(-1 != (read = fin.read(b))){

out.write(b,0,read);

}

怎樣編一個(gè)能實(shí)現(xiàn)文件下載功能的JAVA程序

java實(shí)現(xiàn)文件下載

一、采用RequestDispatcher的方式進(jìn)行

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");//設(shè)置為下載application/x-download

String filenamedownload = "/系統(tǒng)解決方案.doc";//即將下載的文件的相對(duì)路徑

String filenamedisplay = "系統(tǒng)解決方案.doc";//下載文件時(shí)顯示的文件保存名稱

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"%

%

//關(guān)于文件下載時(shí)采用文件流輸出的方式處理:

//加上response.reset(),并且所有的%后面不要換行,包括最后一個(gè);

//因?yàn)锳pplication Server在處理編譯jsp時(shí)對(duì)于%和%之間的內(nèi)容一般是原樣輸出,而且默認(rèn)是PrintWriter,

//而你卻要進(jìn)行流輸出:ServletOutputStream,這樣做相當(dāng)于試圖在Servlet中使用兩種輸出機(jī)制,

//就會(huì)發(fā)生:getOutputStream() has already been called for this response的錯(cuò)誤

//詳細(xì)請(qǐng)見(jiàn)《More Java Pitfill》一書(shū)的第二部分 Web層Item 33:試圖在Servlet中使用兩種輸出機(jī)制 270

//而且如果有換行,對(duì)于文本文件沒(méi)有什么問(wèn)題,但是對(duì)于其它格式,比如AutoCAD、Word、Excel等文件

//下載下來(lái)的文件中就會(huì)多出一些換行符0x0d和0x0a,這樣可能導(dǎo)致某些格式的文件無(wú)法打開(kāi),有些也可以正常打開(kāi)。

response.reset();//可以加也可以不加

response.setContentType("application/x-download");//設(shè)置為下載application/x-download

// /../../退WEB-INF/classes兩級(jí)到應(yīng)用的根目錄下去,注意Tomcat與WebLogic下面這一句得到的路徑不同,WebLogic中路徑最后沒(méi)有/

System.out.println(this.getClass().getClassLoader().getResource("/").getPath());

String filenamedownload = this.getClass().getClassLoader().getResource("/").getPath() + "/../../系統(tǒng)解決方案.doc";

String filenamedisplay = "系統(tǒng)解決方案.doc";//系統(tǒng)解決方案.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 下載文件的方法怎么寫(xiě)

參考下面

public HttpServletResponse download(String path, HttpServletResponse response) {

try {

// path是指欲下載的文件的路徑。

File file = new File(path);

// 取得文件名。

String filename = file.getName();

// 取得文件的后綴名。

String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

// 以流的形式下載文件。

InputStream fis = new BufferedInputStream(new FileInputStream(path));

byte[] buffer = new byte[fis.available()];

fis.read(buffer);

fis.close();

// 清空response

response.reset();

// 設(shè)置response的Header

response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));

response.addHeader("Content-Length", "" + file.length());

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

response.setContentType("application/octet-stream");

toClient.write(buffer);

toClient.flush();

toClient.close();

} catch (IOException ex) {

ex.printStackTrace();

}

return response;

}

// 下載本地文件

public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {

String fileName = "Operator.doc".toString(); // 文件的默認(rèn)保存名

// 讀到流中

InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路徑

// 設(shè)置輸出的格式

response.reset();

response.setContentType("bin");

response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

// 循環(huán)取出流中的數(shù)據(jù)

byte[] b = new byte[100];

int len;

try {

while ((len = inStream.read(b)) 0)

response.getOutputStream().write(b, 0, len);

inStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

// 下載網(wǎng)絡(luò)文件

public void downloadNet(HttpServletResponse response) throws MalformedURLException {

int bytesum = 0;

int byteread = 0;

URL url = new URL("windine.blogdriver.com/logo.gif");

try {

URLConnection conn = url.openConnection();

InputStream inStream = conn.getInputStream();

FileOutputStream fs = new FileOutputStream("c:/abc.gif");

byte[] buffer = new byte[1204];

int length;

while ((byteread = inStream.read(buffer)) != -1) {

bytesum += byteread;

System.out.println(bytesum);

fs.write(buffer, 0, byteread);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

//支持在線打開(kāi)文件的一種方式

public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {

File f = new File(filePath);

if (!f.exists()) {

response.sendError(404, "File not found!");

return;

}

BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));

byte[] buf = new byte[1024];

int len = 0;

response.reset(); // 非常重要

if (isOnLine) { // 在線打開(kāi)方式

URL u = new URL("" + filePath);

response.setContentType(u.openConnection().getContentType());

response.setHeader("Content-Disposition", "inline; filename=" + f.getName());

// 文件名應(yīng)該編碼成UTF-8

} else { // 純下載方式

response.setContentType("application/x-msdownload");

response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());

}

OutputStream out = response.getOutputStream();

while ((len = br.read(buf)) 0)

out.write(buf, 0, len);

br.close();

out.close();

}

Java文件下載怎么實(shí)現(xiàn)的

下載就很簡(jiǎn)單了

把你要下載的文件做成超級(jí)鏈接,可以不用任何組件

比如說(shuō)

下載一個(gè)word文檔

a href="名稱.doc"名稱.doc/a

路徑你自己寫(xiě)

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;

/**

*

* 實(shí)現(xiàn)了下載的功能*/

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); //對(duì)象調(diào)用下載的方法

} 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//下載的方法

{//參數(shù) 下載地址,線程數(shù)量

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection)url.openConnection();//獲取HttpURLConnection對(duì)象

conn.setRequestMethod("GET");//設(shè)置請(qǐng)求格式,這里是GET格式

conn.setReadTimeout(5*1000);//

int filelength = conn.getContentLength();//獲取要下載文件的長(zhǎng)度

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;//每條線程下載的長(zhǎng)度

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

//計(jì)算開(kāi)始位置的公式:線程id*每條線程下載的數(shù)據(jù)長(zhǎng)度=?

//計(jì)算結(jié)束位置的公式:(線程id+1)*每條線程下載數(shù)據(jù)長(zhǎng)度-1=?

int startposition = threadid*block;

int endposition = (threadid+1)*block-1;

try {

try {

RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");

accessFile.seek(startposition);//設(shè)置從什么位置寫(xiě)入數(shù)據(jù)

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下載文件的代碼,java下載文件的代碼是多少
文章地址:http://muchs.cn/article34/hcpose.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)服務(wù)器托管、做網(wǎng)站外貿(mào)建站、移動(dòng)網(wǎng)站建設(shè)、網(wǎng)站策劃

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

網(wǎng)站建設(shè)網(wǎng)站維護(hù)公司