當前位置:首頁 » 編程語言 » java文件與下載

java文件與下載

發布時間: 2022-08-31 20:51:13

1. 用java實現文件的上傳與下載

1.下載簡單,無非是把伺服器上的文件或者資料庫中的BLob(或其他二進制型),用流讀出來,然後寫到客戶端即可,要注意 ContentType。

2.上傳,可以用Apache Commons Upload等開源工具,或者自己寫:
form要用enctype="multipart/form-data"
然後伺服器端也是用IO把客戶端提交的文件流讀入,然後寫到伺服器的文件系統或者資料庫里。不同的資料庫對Lob欄位操作可能有所不同,建議用Hibernate,JPA等成熟的ORM框架,可以不考慮資料庫細節。

2. java 文件和圖片下載處理

用<a>標簽把你的圖片當作鏈接的形式包起來,然後點擊的時候下載的href屬性地址里的文件類容指向你伺服器上的文件

3. java實現文件的上傳和下載

用輸出流 接受 一個下載地址的網路流
然後將這個輸出流 保存到本地一個文件 後綴與下載地址的後綴相同··

上傳的話 將某個文件流 轉成位元組流 上傳到某個webservice方法里

-------要代碼來代碼

URL url=new URL("http://www..com/1.rar");
URLConnection uc=url.openConnection();
InputStream in=uc.getInputStream();
BufferedInputStream bis=new BufferedInputStream(in);
FileOutputStream ft=new FileOutputStream("E://1.rar");

這是下載 上傳太麻煩就不給寫了

4. 通過java實現文件下載

在jsp/servlet中斷點/多線程下載文件
<%@ 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", "www.trydone.com"); 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);%>
是否可以解決您的問題?

5. 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 = "http://www.7cd.cn/QingTengPics/倩女幽魂.mp3";//MP3下載的地址
String path ="http://img.99luna.com/music/%CF%EB%C4%E3%BE%CD%D0%B4%D0%C5.mp3";

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

}

}
}

6. 求問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("file:///" + 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();}

7. JAVA 文件下載問題

如果是本地伺服器的話,應該把文件發布,會生成一個url ,用這個url就可以下載了。

8. 用java實現文件的下載,如何提高下載速度(非web開發)

下面貼出的代碼是一個簡單的讀取遠程文件保存到本地的實現,至於提高下載速度你可以利用多線程,具體可參考最下面的那個網址——

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class DownloadTester {
public static void main(String[] args) throws IOException {
String urlStr = "https://gss0.bdstatic.com/70cFsjip0QIZ8tyhnq/img/logo-.gif";
String path = "D:/";

String name = urlStr.substring(urlStr.trim().lastIndexOf("/"));

URL url = new URL(urlStr);
InputStream in = url.openConnection().getInputStream();

File file = new File(path + name);
FileOutputStream out = new FileOutputStream(file, true);

int counter = 0;
int ch;
byte[] buffer = new byte[1024];
while ((ch = in.read(buffer)) != -1) {
out.write(buffer, 0, ch);
counter += ch;

System.out.println(counter + ":byte");
}
out.flush();
in.close();
out.close();
}
}

9. 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組件,去網上下個就行了,也有介紹的

熱點內容
電腦登陸加密 發布:2025-01-16 05:21:57 瀏覽:152
安卓怎麼修復閃退 發布:2025-01-16 05:21:54 瀏覽:554
易盾加密 發布:2025-01-16 05:20:51 瀏覽:894
html上傳圖片的代碼 發布:2025-01-16 05:16:55 瀏覽:601
搭建伺服器租用電信的怎麼樣 發布:2025-01-16 05:12:32 瀏覽:49
phpmysql源碼下載 發布:2025-01-16 05:12:31 瀏覽:211
python安裝依賴包 發布:2025-01-16 05:11:45 瀏覽:996
澳門雲主機品牌伺服器 發布:2025-01-16 05:06:55 瀏覽:769
資料庫設計主要內容 發布:2025-01-16 05:02:02 瀏覽:13
存儲過程如何修改 發布:2025-01-16 05:01:55 瀏覽:634