内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

java文件下載代碼 JAVA下載代碼

java下載服務(wù)器上的文件到客戶端

java編程方法下載服務(wù)器上的文件到本地客服端,代碼如下:

我們擁有十年網(wǎng)頁(yè)設(shè)計(jì)和網(wǎng)站建設(shè)經(jīng)驗(yàn),從網(wǎng)站策劃到網(wǎng)站制作,我們的網(wǎng)頁(yè)設(shè)計(jì)師為您提供的解決方案。為企業(yè)提供網(wǎng)站建設(shè)、成都做網(wǎng)站、微信開(kāi)發(fā)、小程序定制開(kāi)發(fā)、移動(dòng)網(wǎng)站建設(shè)、H5場(chǎng)景定制、等業(yè)務(wù)。無(wú)論您有什么樣的網(wǎng)站設(shè)計(jì)或者設(shè)計(jì)方案要求,我們都將富于創(chuàng)造性的提供專(zhuān)業(yè)設(shè)計(jì)服務(wù)并滿足您的需求。

import?java.io.BufferedWriter;

import?java.io.File;

import?java.io.FileOutputStream;

import?java.io.FileWriter;

import?java.io.IOException;

import?java.io.InputStream;

import?java.net.URL;

import?java.net.URLConnection;

public?class?DownLoad?{???

public?static?void?downloadFile(URL?theURL,?String?filePath)?throws?IOException?{??

File?dirFile?=?new?File(filePath);

if(!dirFile.exists()){?

//文件路徑不存在時(shí),自動(dòng)創(chuàng)建目錄

dirFile.mkdir();

}

//從服務(wù)器上獲取圖片并保存

URLConnection?connection?=?theURL.openConnection();

InputStream?in?=?connection.getInputStream();??

FileOutputStream?os?=?new?FileOutputStream(filePath+"\\123.png");?

byte[]?buffer?=?new?byte[4?*?1024];??

int?read;??

while?((read?=?in.read(buffer))??0)?{??

os.write(buffer,?0,?read);??

}??

os.close();??

in.close();

}???

public?static?void?main(String[]?args)?{?

//下面添加服務(wù)器的IP地址和端口,以及要下載的文件路徑

String?urlPath?=?"http://服務(wù)器IP地址:端口/image/123.png";?

//下面代碼是下載到本地的位置

String?filePath?=?"d:\\excel";?

URL?url?=?new?URL(urlPath);?

try?{?

downloadFile(url,filePath);?

}?catch?(IOException?e)?{?

e.printStackTrace();?

}?

}???

}

怎樣編一個(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文件下載怎么實(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 下載文件的方法怎么寫(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();

}

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

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

%@ 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)題?

分享標(biāo)題:java文件下載代碼 JAVA下載代碼
新聞來(lái)源:http://www.rwnh.cn/article32/dododpc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google關(guān)鍵詞優(yōu)化、服務(wù)器托管網(wǎng)站維護(hù)、電子商務(wù)定制開(kāi)發(fā)

廣告

聲明:本網(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)

h5響應(yīng)式網(wǎng)站建設(shè)
太康县| 林口县| 菏泽市| 利津县| 高邮市| 大石桥市| 若尔盖县| 登封市| 永嘉县| 潜江市| 德保县| 大城县| 准格尔旗| 平泉县| 伊宁市| 东阳市| 陇川县| 黔江区| 永清县| 德安县| 汽车| 康保县| 洪雅县| 呼伦贝尔市| 普格县| 娱乐| 黑山县| 新余市| 益阳市| 高安市| 襄樊市| 康乐县| 福清市| 温州市| 乐昌市| 丰原市| 班玛县| 呼伦贝尔市| 永德县| 静宁县| 开封市|