本文目錄一覽:
JAVA文件下載如何實現
在http協議下,實現下載一般就兩種方法,一個採用cont-type=””;此種方法為附件的方式下載;;
另一種較簡單,就是你只需要點下載按鈕然後跳轉到服務器的那個文件路勁就可以了,瀏覽器自動回進行下載..
java 文件下載
這很奇怪啊,下載怎麼會影響到Js腳本呢,看你的下載程序,這相當於一個完整的交互過程,如果要提出改進建議,我會說,你完全浪費 BufferedInputStream的優勢,尤其是這句
byte[] buffer = new byte[fis.available()];
簡直是敗筆中的敗筆,如果是個100m的文件,這要佔多少內存?
建議這樣使用:
byte[] buffer=new byte[4096];
int readByte=0;
while((readByte=fis.read(buffer)0){
toClient.write(buffer,0,readByte);
}
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();
// 設置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(); // 文件的默認保存名
// 讀到流中
InputStream inStream = new FileInputStream(“c:/Operator.doc”);// 文件的存放路徑
// 設置輸出的格式
response.reset();
response.setContentType(“bin”);
response.addHeader(“Content-Disposition”, “attachment; filename=\”” + fileName + “\””);
// 循環取出流中的數據
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();
}
}
// 下載網絡文件
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());
// 文件名應該編碼成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文件下載的幾種方式
InputStream fis = new BufferedInputStream(new FileInputStream(path));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();// 清空responseresponse.reset();// 設置response的Headerresponse.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(); // 文件的默認保存名// 讀到流中InputStream inStream = new FileInputStream(“c:/Operator.doc”);// 文件的存放路徑// 設置輸出的格式response.reset();response.setContentType(“bin”);response.addHeader(“Content-Disposition”, “attachment; filename=\”” + fileName + “\””);// 循環取出流中的數據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();}}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());// 文件名應該編碼成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文件下載怎麼實現的
下載就很簡單了
把你要下載的文件做成超級鏈接,可以不用任何組件
比如說
下載一個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 = “倩女幽魂.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 如何下載文件?
我用struts2給你實現:
1.首先struts2.xml 裏面
action name=”download” class=”com.zfj.action.DownloadAction”
!– 注意這裡不再是返回一個字符串找到一個頁面了
從服務器返回到本地客戶端是一個流 我們需要配置流信息
type:表示接受方式或者跳轉方法是
默認是 dispatcher 請求轉發,所以之前我們一般不書寫這個參數但是這裡需要更改為stream重定向
—
result type=”stream”
!–
因為之前我們設置的execute方法返回一個String,但是我們現在需要返回一個流。這裡我們要指定一個新的方法為我們處理業務邏
輯並且返迴流所以默認execute 方法對我們沒有作用了,在這裡我們指定一個新的方法為我們處理業務邏輯並且最後返迴流
這裡的inputName是固定寫法 後面的名字dname要跟 action裏面的getDname對應
—
param name=”inputName”dname/param
!– 當流返回過來時,我們應當設置頭信息
給瀏覽器,這裡設置的都是流信息
name裏面的是固定寫法
attachment:表示使用附件下載
online:直接打開
分號後的filename是固定寫法,後面通過一個ognl表達式
引用下載的文件名
—
param name=”contentDisposition”attachment;filename=${filename}/param
/result
/action
這裡不再是返回一個字符串找到一個頁面了。從服務器返回到本地客戶端是一個流,我們需要配置流信息。
type:表示接受方式或者跳轉方式是(默認是dispathcher請求轉發,所以之前我們一般不書寫這個,但是這裡下載需要更改stream)
2.對應的DownloadAction
@Override
public String execute() throws Exception {
return this.SUCCESS;
}
//這裡的getEtoak要跟struts.xml里的inputName的值對應
public InputStream getEtoak() throws Exception {
return new FileInputStream(
ServletActionContext.getServletContext()
.getRealPath(“/image”)
+ “/”
+ this.getFilename());
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/308378.html