java的下载代码 java实现下载

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"), " ", " ");
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实现自动下载的源代码您好,这样的:
/**
*
*/
package com.b510.base.bean.install;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author hongten(hongtenzone@foxmail.com)
* @date 2013-2-24
*/
@SuppressWarnings("unchecked")
public class BeanUtils {
//公共部分
private static final String RT_1 = "\r\n";
private static final String RT_2 = RT_1 RT_1;
private static final String BLANK_1 =" ";
private static final String BLANK_4 ="";
private static final String BLANK_8 =BLANK_4BLANK_4;
//注释部分
private static final String ANNOTATION_AUTHOR_PARAMTER = "@author ";
private static final String ANNOTATION_AUTHOR_NAME = "hongten(hongtenzone@foxmail.com)";
private static final String ANNOTATION_AUTHOR = ANNOTATION_AUTHOR_PARAMTERANNOTATION_AUTHOR_NAME;
private static final String ANNOTATION_DATE = "@date ";
private static final String ANNOTATION = "/**" RT_1 BLANK_1 "*" BLANK_1 ANNOTATION_AUTHORRT_1 BLANK_1 "*" BLANK_1 ANNOTATION_DATEgetDate() RT_1 BLANK_1 "*/" RT_1;
//文件 地址
//private static final String BEAN_PATH = "com/b510/base/bean";
private static final String DAO_PATH = "com/b510/base/dao";
private static final String DAO_IMPL_PATH = "com/b510/base/dao/impl";
private static final String SERVICE_PATH = "com/b510/base/service";
private static final String SERVICE_IMPL_PATH = "com/b510/base/service/impl";
//包名
private static final String BEAN_URL = "com.b510.base.bean";
private static final String DAO_URL = "com.b510.base.dao";
private static final String DAO_IMPL_URL = "com.b510.base.dao.impl";
private static final String SERVICE_URL = "com.b510.base.service";
private static final String SERVICE_IMPL_URL = "com.b510.base.service.impl";
//基本类名称
private static final String BASE_DAO_NAME = DAO_URL".BaseDao";
private static final String ABSTRACT_BASE_DAO_IMPL_NAME = DAO_IMPL_URL".AbstractBaseDaoImpl";
private static final String BASE_SERVICE_NAME = SERVICE_URL".BaseService";
private static final String ABSTRACT_BASE_SERVICE_IMPL_NAME = SERVICE_IMPL_URL".AbstractBaseServiceImpl";
/**
* 创建bean的Daobr
*
* @param c
* @throws Exception
*/
public void createBeanDao(Class c) throws Exception {
String cName = c.getName();
String fileName = System.getProperty("user.dir")"/src/"DAO_PATH
"/"getLastChar(cName)"Dao.java";
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write("package " DAO_URL ";" RT_2 ANNOTATION "public interface "
getLastChar(cName)"Dao extends " BASE_DAO_NAME " "cName" {" RT_2 "}");
fw.flush();
fw.close();
showInfo(fileName);
}
/**
* 创建bean的Dao的实现类
* @param c
* @throws Exception
*/
public void createBeanDaoImpl(Class c) throws Exception{
String cName = c.getName();
String fileName = System.getProperty("user.dir")"/src/"DAO_IMPL_PATH
"/"getLastChar(cName)"DaoImpl.java";
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write("package " DAO_IMPL_URL ";" RT_2 ANNOTATION "public class "
getLastChar(cName)"DaoImpl extends " ABSTRACT_BASE_DAO_IMPL_NAME ""
cName" implements " DAO_URL "." getLastChar(cName) "Dao{" RT_2 "}");
fw.flush();
fw.close();
showInfo(fileName);
}
/**
* 创建bean的service
* @param c
* @throws Exception
*/
public void createBeanService(Class c) throws Exception{
String cName = c.getName();
String fileName = System.getProperty("user.dir")"/src/"SERVICE_PATH
"/"getLastChar(cName)"Service.java";
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write("package " SERVICE_URL ";" RT_2 ANNOTATION "public interface "
getLastChar(cName)"Service extends " BASE_SERVICE_NAME ""cName"{" RT_2 "}");
fw.flush();
fw.close();
showInfo(fileName);
}
/**
* 创建bean的service的实现类
* @param c
* @throws Exception
*/
public void createBeanServiceImpl(Class c) throws Exception{
String cName = c.getName();
String fileName = System.getProperty("user.dir")"/src/"SERVICE_IMPL_PATH
"/"getLastChar(cName) "ServiceImpl.java";
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write("package " SERVICE_IMPL_URL ";" RT_2 ANNOTATION "public class "
getLastChar(cName)"ServiceImpl extends " ABSTRACT_BASE_SERVICE_IMPL_NAME ""cName
" implements " SERVICE_URL "." getLastChar(cName) "Service{" RT_2 BLANK_4
"private " DAO_URL "." getLastChar(cName) "Dao " getLowercaseChar(getLastChar(cName))
"Dao;" RT_2 BLANK_4 "public void set" getLastChar(cName) "Dao(" DAO_URL "." getLastChar(cName) "Dao "
getLowercaseChar(getLastChar(cName)) "Dao){" RT_1 BLANK_8 "this." getLowercaseChar(getLastChar(cName)) "Dao = "
getLowercaseChar(getLastChar(cName)) "Dao;" RT_1 BLANK_4 "}" RT_2 BLANK_4 "@Override" RT_1 BLANK_4
"public " DAO_URL "." "BaseDao" BEAN_URL "." getLastChar(cName) " getBaseDao(){" RT_1 BLANK_8
"return " getLowercaseChar(getLastChar(cName)) "Dao;" RT_1 BLANK_4 "}" RT_2 "}");
fw.flush();
fw.close();
showInfo(fileName);
}
/**
* 获取路径的最后面字符串br
* 如:br
*codestr = "com.b510.base.bean.User"/codebr
*code return "User";code
* @param str
* @return
【java的下载代码 java实现下载】*/
public String getLastChar(String str) {
if ((str != null)(str.length()0)) {
int dot = str.lastIndexOf('.');
if ((dot-1)(dot(str.length() - 1))) {
return str.substring(dot1);
}
}
return str;
}
/**
* 把第一个字母变为小写br
* 如:br
*codestr = "UserDao";/codebr
*codereturn "userDao";/code
* @param str
* @return
*/
public String getLowercaseChar(String str){
return str.substring(0,1).toLowerCase() str.substring(1);
}
/**
* 显示信息
* @param info
*/
public void showInfo(String info){
System.out.println("创建文件:"info"成功!");
}
/**
* 获取系统时间
* @return
*/
public static String getDate(){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(new Date());
}
}
java下载方面的代码你java的下载代码的这段代码有两处让人疑惑 。其一、File()这个构造函数java的下载代码,自已查下API
其二、FileOutputStreamjava的下载代码,FileOutputStream(String name)创建一个向具有指定名称的文件中写入数据的输出文件流 。它只是创建java的下载代码了一个输出流,其中没有具体的值,那么这个值来自哪呢,其就来自于你的输入流 。其中FileOutputStream()中只是创建了一个字节输出流,其只能接受字节流的输出,所以它还需要与DataOutputStream()的配合才能完成输出,具体用法你可以查API
Java文件下载怎么实现的下载就很简单了
把你要下载的文件做成超级链接,可以不用任何组件
比如说
下载一个word文档
a href="https://www.04ip.com/post/名称.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; iupload.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的下载代码的介绍就聊到这里吧,感谢你花时间阅读本站内容 , 更多关于java实现下载、java的下载代码的信息别忘了在本站进行查找喔 。

    推荐阅读