java附件下载
❶ 求问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();}
❷ Java文件下载问题
spring MVC下载文件
❸ java如何下载domino文档附件到本地
Domino也是支持复Java程序的啊,如果你想下载制Domino的附件可以用servlet,domino是支持servelet的,在servlet中调用Domino的classDatabase,View 和Document ,RichTextItem和EmbeddedObject 这些类,就可以实现附件的下载,当然 是通过HTTP。
如果用java程序直接连接Domino服务器的话,需要启动domino的DIIOP服务器,通过这个接口也可以实现。不过之前需要做些功课,先了解下Domino的开发知识。
❹ JAVA在开发附件下载问题
1)http头当中确实需要指定当前返回的是文件,才能让浏览器按照文件识别,但是你说你写了setheader,就应该知道 默认文件名也是在这里写的,所以你说“不正常”就很难明白了。
2)迅雷的任务栏里有没有同名文件,你是拿不到的,那不是B/S结构能处理的东西。当然你可以写一个插件来处理,不过这东西一点都不简单。举个栗子,如果你的java(也就是服务器)能够知道用户的迅雷里有什么,那么用户那儿还有啥你不知道的,岂不是登录你的网站我下了多少毛片都被你晓得了?
3)你看到的有些东西是迅雷处理的,建议你把迅雷的插件关闭了,先把其他功能弄完整了再把迅雷加上。
❺ java下载文件
http是流传输,一次请求中你是不能将流截断的,如果想做到你说的只有两种形式专:
1、就是你使用的方式,属多段读取(其实就是断点续传的原理),多个请求,每个请求请求一部分,如果你觉得效率低可以从两方面优化:
(1)不要用URLConnecion,而使用HttpClient之类的工具包进行请求
(2)使用多线程并发请求,其实就是断点续传了,迅雷就是几个线程一起下嘛
2、只请求一次,请求全部的,将全部流缓存到内存中(byte[]),然后根据你的需要分段截取,写入文件
❻ 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();
}
}
}
}
❼ JAVA 文件下载问题
package Task;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class HttpDownload {
private String file_url;
private String file_path;
private String file_name;
private String logo_url;
private String logo_path;
private String logo_name;
public void setLogo_name(String logoUrl) {
.logo_name = logoUrl.substring(logoUrl.lastIndexOf("/"));
}
public void setLogo_path(String logoUrl) {
String Path = "d:\\logo";
String partPath = logo_name.substring(1,logo_name.lastIndexOf("."));
this.logo_path = Path ;
List<String> list = new ArrayList<String>();
int beginIndex = 1;
int endIndex = 4;
while(beginIndex<partPath.length()-1){
if(endIndex>partPath.length()-1) endIndex = partPath.length();
String name = partPath.substring(beginIndex, endIndex);
if(name.length()<3){
for(int i = name.length();i<3;i++){
name+=0;
}
}
list.add(name);
beginIndex += 3;
endIndex += 3;
}
for(String s:list){
logo_path += "\\"+s;
}
System.out.println(logo_path);
}
public void setFile_name(String file_name) {
this.file_name = file_name.substring(file_name.lastIndexOf("/"));
}
public boolean downLoadFile(String sURL,String name,String path) {
int nStartPos = 0;
int nRead = 0;
try {
URL url = new URL(sURL);
// 打开连接
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
// 获得文件长度
long nEndPos = getFileSize(sURL);
File file = new File(path);
file.mkdirs();
RandomAccessFile oSavedFile = new RandomAccessFile(path + "\\"
+ name, "rw");
httpConnection
.setRequestProperty("User-Agent", "Internet Explorer");
String sProperty = "bytes=" + nStartPos + "-";
// 告诉服务器,这个文件从nStartPos字节开始传
httpConnection.setRequestProperty("RANGE", sProperty);
System.out.println(name+"下载开始:"+sProperty);
InputStream input = httpConnection.getInputStream();
byte[] b = new byte[1024];
// 读取网络文件,写入指定的文件中
while ((nRead = input.read(b, 0, 1024)) > 0 && nStartPos < nEndPos) {
oSavedFile.write(b, 0, nRead);
nStartPos += nRead;
}
httpConnection.disconnect();
System.out.println(name+"文件下载结束!");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public String getFile_url() {
return file_url;
}
public void setFile_url(String file_url) {
this.file_url = file_url;
}
public String getFile_path() {
return file_path;
}
public void setFile_path() {
this.file_path = "D:\\soft";
}
public String getFile_name() {
return file_name;
}
// 获得文件长度
public static long getFileSize(String sURL) {
int nFileLength = -1;
try {
URL url = new URL(sURL);
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
httpConnection
.setRequestProperty("User-Agent", "Internet Explorer");
int responseCode = httpConnection.getResponseCode();
if (responseCode >= 400) {
System.err.println("Error Code : " + responseCode);
return -2; // -2 represent access is error
}
String sHeader;
for (int i = 1;; i++) {
sHeader = httpConnection.getHeaderFieldKey(i);
if (sHeader != null) {
if (sHeader.equals("Content-Length")) {
nFileLength = Integer.parseInt(httpConnection
.getHeaderField(sHeader));
break;
}
} else
break;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(nFileLength);
return nFileLength;
}
public String getLogo_url() {
return logo_url;
}
public void setLogo_url(String logo_url) {
this.logo_url = logo_url;
}
public String getLogo_name() {
return logo_name;
}
public String getLogo_path() {
return logo_path;
}
}
这是跑在我服务器上的下载程序你可以看看希望对你有帮助,有问题问就好了
❽ 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实现下载文件(包括图片)
/**
*
* @param f
* 保存的文件
* @param imgUrl
* 图片地址
*/
public void down(File f, String imgUrl) {
byte[] buffer = new byte[8 * 1024];
URL u;
URLConnection connection = null;
try {
u = new URL(imgUrl);
connection = u.openConnection();
} catch (Exception e) {
System.out.println("ERR:" + imgUrl);
return;
}
connection.setReadTimeout(100000);
InputStream is = null;
FileOutputStream fos = null;
try {
f.createNewFile();
is = connection.getInputStream();
fos = new FileOutputStream(f);
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (Exception e) {
f.delete();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
buffer = null;
// System.gc();
}
❿ java实现文件下载的问题
两种办法:
1、在服务器配置里设定一个WebApp的定制目录,把目录指向你D盘的文件目录。
2、在原先的WebApp里写一个Servlet读取D盘的文件,然后把文件内容返回给浏览器。