java下载文件代码 java下载安装包
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中文件下载该怎么写代码求高手指导
if (upfile.exists()) {
bytes = FileUtils.readFileToByteArray(upfile);
response.setContentType("application/x-download");
String agent = request.getHeader("USER-AGENT");//用户代理
// 防止中文文件名乱码
if (null != agent -1 != agent.indexOf("MSIE")) {
String codedfilename = StringUtils.replace(URLEncoder.encode(fileName, "UTF-8"), "+", "%20");
response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
} else if (null != agent -1 != agent.indexOf("Mozilla")) {
String codedfilename = MimeUtility.encodeText(fileName, "UTF-8", "B");
response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
} else {
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
}
response.setContentLength(bytes.length);
response.getOutputStream().write(bytes);
}
java 代码实现下载.doc文件
%@ page contentType="text/html; charset=gb2312" %
%@ page import="java.io.*"%
%!
public String toUtf8String(String s)
{
StringBuffer sb = new StringBuffer();
for (int i=0;is.length();i++) {
char c = s.charAt(i);
if (c = 0 c = 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j b.length; j++) {
int k = b[j];
if (k 0) k += 256;
sb.append("%" + Integer.toHexString(k).
toUpperCase());
}
}
}
return sb.toString();
}
%
%
String filename=new String(request.getParameter("filename").getBytes("ISO8859-1"),"GBK");
String dirName="D:/我.doc";
java.io.File ff=null;
String dd=dirName+System.getProperties().getProperty("file.separator")+filename;
try{
ff=new java.io.File(dd);
}
catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
if (ff!=nullff.exists()ff.isFile())
{
long filelength = ff.length();
InputStream inStream=new FileInputStream(dd);
//设置输出的格式
response.reset();
response.setContentType("application/x-msdownload");
response.setContentLength((int)filelength);
response.addHeader("Content-Disposition","attachment; filename=\"" + toUtf8String(filename) + "\"");
//循环取出流中的数据
byte[] b = new byte[100];
int len;
while((len=inStream.read(b)) 0)
response.getOutputStream().write(b,0,len);
inStream.close();
out.clear();
out = pageContext.pushBody();
}
%
:a href="d.jsp"aa/a
上面的那个是用流写的 但是也可以用超链接下载
你写上文件的路径就可以了
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的上传下载
package com.java.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileAction extends ActionSupport {
/**
* 用于上传的变量
*/
//封装该文件域对应的文件内容
private File[] upload;
//封装该文件域对应的文件的文件名
private String[] uploadFileName;
//封装该文件域对应的文件的文件类型
private String[] uploadContentType;
/**
* 用于下载的变量
*/
private String[] fileNames;
private String fileName;
/**
* 设置getter和setter
* @return
*/
public String[] getFileNames() {
return fileNames;
}
public File[] getUpload() {
return upload;
}
public void setUpload(File[] upload) {
this.upload = upload;
}
public String[] getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String[] getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setFileNames(String[] fileNames) {
this.fileNames = fileNames;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* 用于上传文件的方法
* @return
*/
public String upload(){
//设置文件上传到的位置
String path = ServletActionContext.getServletContext().getRealPath("/file");
//设置文件目标
try {
for (int i = 0; i upload.length; i++) {
File target = new File(path, uploadFileName[i]);
FileUtils.copyFile(upload[i], target);
}
return SUCCESS;
} catch (IOException e) {
e.printStackTrace();
}
return INPUT;
}
/**
* 得到所有上传的文件的名称
* @return
*/
public String fileList(){
String path = ServletActionContext.getServletContext().getRealPath("/file");
fileNames = new File(path).list();
return SUCCESS;
}
/**
* 用于下载文件的方法
* @return
*/
public InputStream getInputStream(){
if(fileName==null || fileName.isEmpty()) return null;
String path = ServletActionContext.getServletContext().getRealPath("/file");
try {
return new FileInputStream(new File(path,fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public String getContentDisposition(){
try {
if(fileName==null||fileName.isEmpty()){
return "inline";
}
return "attachment;filename="+URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "inline";
}
}
比java的io方便多了
帮我看看这段java下载代码,文件名为中文时,报错,无法找到指定文件
代码一共6句,前4句没问题,运行下载是ok的,
最后一句有点不明白,为什么用BufferedInputStream?这个是读文件的,不知道你后面是如何写的,难道还要把文件读到内存?在向客户端发送出去??这样的话下载GB级文件内存溢出。
BufferedInputStream和BufferedOutputStream 用了之后,一定要flush(),这样也许会解决你的中文下载报错。
我直接用BufferedOutputStream 下载文件成功,前面是用你的,后面如下:
InputStream in = new FileInputStream(file);// 将文件装换成缓冲流
OutputStream out = response.getOutputStream(); // 获取response中得下载对象
BufferedOutputStream bufo = new BufferedOutputStream(out); // 对象转换成字符流
int length = 0; // 读取本地文时,记录本次文件读取内容大小
byte[] buffer = new byte[524288]; // 每次推送 512KB
while ((length = in.read(buffer)) != -1) // 读取本地文件,并在存放在buffer 数组
{
bufo.write(buffer, 0, length);// 预备向客户端推送
bufo.flush();// 清空缓存,并立即推送
}
in.close();
out.close();
bufo.close();
不建议写 response.setContentLength(int); 大并发时,这个容易出问题。
网站名称:java下载文件代码 java下载安装包
分享地址:http://cdiso.cn/article/dodpoep.html