下載就很簡單了
把你要下載的文件做成超級鏈接,可以不用任何組件
比如說
下載一個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();
}
}
}
}
㈡ 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("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();
}
㈢ java FTP下載文件在代碼中如何實現知道下載完成
(KmConfigkmConfig,StringfileName,StringclientFileName,OutputStreamoutputStream){
try{
StringftpHost=kmConfig.getFtpHost();
intport=kmConfig.getFtpPort();
StringuserName=kmConfig.getFtpUser();
StringpassWord=kmConfig.getFtpPassword();
Stringpath=kmConfig.getFtpPath();
FtpClientftpClient=newFtpClient(ftpHost,port);//ftpHost為FTP伺服器的IP地址,port為FTP伺服器的登陸埠,ftpHost為String型,port為int型。
ftpClient.login(userName,passWord);//userName、passWord分別為FTP伺服器的登陸用戶名和密碼
ftpClient.binary();
ftpClient.cd(path);//path為FTP伺服器上保存上傳文件的路徑。
try{
TelnetInputStreamin=ftpClient.get(fileName);
byte[]bytes=newbyte[1024];
intcnt=0;
while((cnt=in.read(bytes,0,bytes.length))!=-1){
outputStream.write(bytes,0,cnt);
}
//##############################################
//這里文件就已經下載完了,自己理解一下
//#############################################
outputStream.close();
in.close();
}catch(Exceptione){
ftpClient.closeServer();
e.printStackTrace();
}
ftpClient.closeServer();
}catch(Exceptione){
System.out.println("下載文件失敗!請檢查系統FTP設置,並確認FTP服務啟動");
}
}
㈣ 用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 = "http://img..com/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();
}
}
㈤ 怎樣編一個能實現文件下載功能的JAVA程序
java實現文件下載
一、採用RequestDispatcher的方式進行
1、web.xml文件中增加
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
2、程序如下:
<%@page language="java" import="java.net.*" pageEncoding="gb2312"%>
<%
response.setContentType("application/x-download");//設置為下載application/x-download
String filenamedownload = "/系統解決方案.doc";//即將下載的文件的相對路徑
String filenamedisplay = "系統解決方案.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>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
2、程序如下:
<%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*" pageEncoding="gb2312"%>
<%
//關於文件下載時採用文件流輸出的方式處理:
//加上response.reset(),並且所有的%>後面不要換行,包括最後一個;
//因為Application Server在處理編譯jsp時對於%>和<%之間的內容一般是原樣輸出,而且默認是PrintWriter,
//而你卻要進行流輸出:ServletOutputStream,這樣做相當於試圖在Servlet中使用兩種輸出機制,
//就會發生:getOutputStream() has already been called for this response的錯誤
//詳細請見《More Java Pitfill》一書的第二部分 Web層Item 33:試圖在Servlet中使用兩種輸出機制 270
//而且如果有換行,對於文本文件沒有什麼問題,但是對於其它格式,比如AutoCAD、Word、Excel等文件
//下載下來的文件中就會多出一些換行符0x0d和0x0a,這樣可能導致某些格式的文件無法打開,有些也可以正常打開。
response.reset();//可以加也可以不加
response.setContentType("application/x-download");//設置為下載application/x-download
// /../../退WEB-INF/classes兩級到應用的根目錄下去,注意Tomcat與WebLogic下面這一句得到的路徑不同,WebLogic中路徑最後沒有/
System.out.println(this.getClass().getClassLoader().getResource("/").getPath());
String filenamedownload = this.getClass().getClassLoader().getResource("/").getPath() + "/../../系統解決方案.doc";
String filenamedisplay = "系統解決方案.doc";//系統解決方案.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 代碼實現下載.doc文件
搞那麼復雜..直接把#變成.doc文件的相對路徑就行了...
㈦ 用java下載指定路徑下的文件夾,下載內容包含指定文件夾及其包含的文件夾子文件!!!
public static void main(String[] args) throws InterruptedException {
// 指定文件夾
File file = new File("D:\\downloads\\");
List<File> fileList = null;
// 包含字元
String filter = "j";
if (file != null) {
if (file.isDirectory()) {
File[] fileArray = file.listFiles();
if (fileArray != null && fileArray.length > 0) {
fileList = new ArrayList<File>();
// 包括文件,文件夾的判斷
for (File f : fileArray) {
String fileName = f.getName();
if (fileName.indexOf(filter) != -1) {
fileList.add(f);
}
}
}
} else {
System.out.println("Not Directory.");
}
}
if (fileList != null && fileList.size() > 0) {
for (File f : fileList) {
System.out.println(f.getName());
}
}
}
希望對你有所幫助。。。
㈧ 用Java的三大框架實現文件的上傳下載,求代碼啊,最好是分為action,service,serv
package cn.itcast.struts2.demo1;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 完成文件上傳 (不是解析上傳內容,因為上傳內容 由fileUpload攔截器負責解析)
*
* @author seawind
*
*/
public class UploadAction extends ActionSupport {
// 接收上傳內容
// <input type="file" name="upload" />
private File upload; // 這里變數名 和 頁面表單元素 name 屬性一致
private String uploadContentType;
private String uploadFileName;
public void setUpload(File upload) {
this.upload = upload;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
@Override
public String execute() throws Exception {
if (upload == null) { // 通過xml配置 required校驗器 完成校驗
// 沒有上傳文件
return NONE;
}
// 將上傳文件 保存到伺服器端
// 源文件 upload
// 目標文件
File destFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload") + "/" + uploadFileName);
// 文件復制 使用commons-io包 提供 工具類
FileUtils.File(upload, destFile);
return NONE;
}
}
多文件上傳
package cn.itcast.struts2.demo1;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 支持多文件上傳
*
* @author seawind
*
*/
public class MultiUploadAction extends ActionSupport {
// 接收多文件上傳參數,提供數組接收就可以了
private File[] upload;
private String[] uploadContentType;
private String[] uploadFileName;
public void setUpload(File[] upload) {
this.upload = upload;
}
public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
@Override
public String execute() throws Exception {
for (int i = 0; i < upload.length; i++) {
// 循環完成上傳
File srcFile = upload[i];
String filename = uploadFileName[i];
// 定義目標文件
File destFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload" + "/" + filename));
FileUtils.File(srcFile, destFile);
}
return NONE;
}
}
㈨ 怎樣通過java實現伺服器上文件下載
用HttpClient(commons httpclient)包,模擬一個Get請求,發送到網址172.16.30.230/文件地址。這個文件地址不能是E/Map/123.txt,必須是暴露在服務專器屬中的應用里的。就像你寫的應用里的一個jsp頁面的目錄。
成功發送get請求後,就會得到response,裡面有流。就是你下載的文件,然後可以通過FileOutputStream,指定你輸出目錄,寫到磁碟上。
㈩ uc雲盤存的視頻不能看了,什麼時候才能恢復下載播放哪!
這個已經恢復了,之前那段時間是官方在整理和修復所以無法觀看。
UC網盤是一款基於UC瀏覽器的雲存儲服務,提供手機用戶數據存儲,管理和分享等功能。覆蓋了android,symbian,java,wp,iphone等主流的手機平台,利用UC網盤,手機用戶可以安全備份手機本地數據,免流量下載網路資源和論壇分享文件。
文件中轉
文件中轉站是UC推出的一項文件臨時存儲服務,享有較大的存儲空間。結合瀏覽器的離線下載功能,方便用戶下載網路資源,在過程中為用戶節省時間,節約流量。普通用戶享受4G免費空間和7天的文件保存期限。