成人午夜视频全免费观看高清-秋霞福利视频一区二区三区-国产精品久久久久电影小说-亚洲不卡区三一区三区一区

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

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

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

我們擁有十年網(wǎng)頁設(shè)計和網(wǎng)站建設(shè)經(jīng)驗(yàn),從網(wǎng)站策劃到網(wǎng)站制作,我們的網(wǎng)頁設(shè)計師為您提供的解決方案。為企業(yè)提供網(wǎng)站建設(shè)、成都做網(wǎng)站、微信開發(fā)、小程序定制開發(fā)、移動網(wǎng)站建設(shè)、H5場景定制、等業(yè)務(wù)。無論您有什么樣的網(wǎng)站設(shè)計或者設(shè)計方案要求,我們都將富于創(chuàng)造性的提供專業(yè)設(shè)計服務(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()){?

//文件路徑不存在時,自動創(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();?

}?

}???

}

怎樣編一個能實(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";//即將下載的文件的相對路徑

String filenamedisplay = "系統(tǒng)解決方案.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"%

%

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

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

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

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

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

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

//而且如果有換行,對于文本文件沒有什么問題,但是對于其它格式,比如AutoCAD、Word、Excel等文件

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

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

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

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

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)的

下載就很簡單了

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

比如說

下載一個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;

/**

*

* 實(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); //對象調(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對象

conn.setRequestMethod("GET");//設(shè)置請求格式,這里是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*每條線程下載的數(shù)據(jù)長度=?

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

int startposition = threadid*block;

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

try {

try {

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

accessFile.seek(startposition);//設(shè)置從什么位置寫入數(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 下載文件的方法怎么寫

參考下面

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

}

}

//支持在線打開文件的一種方式

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) { // 在線打開方式

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)文件下載

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

是否可以解決您的問題?

分享標(biāo)題:java文件下載代碼 JAVA下載代碼
新聞來源:http://jinyejixie.com/article32/dododpc.html

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

廣告

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

h5響應(yīng)式網(wǎng)站建設(shè)
朔州市| 莲花县| 武平县| 富川| 汝南县| 涿州市| 丹东市| 天峨县| 黔西| 闵行区| 大连市| 丹阳市| 辽源市| 两当县| 平原县| 伊春市| 富蕴县| 丰城市| 平山县| 南岸区| 沂源县| 历史| 溆浦县| 九江县| 伊宁市| 葫芦岛市| 墨玉县| 锡林浩特市| 泸水县| 沛县| 旌德县| 永修县| 永安市| 宝丰县| 盐亭县| 丰都县| 浏阳市| 景德镇市| 石棉县| 江永县| 金寨县|