import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 文件上传工具
* @Description
* @Author iechenyb
* @Date 2013-11-12 下午6:05:02
* @ModHistory
*
*/
public class FileUtils {
private static final int BUFFER_SIZE = 1024*1024*20;//每次写入20m(可修改)
public InputStream in = null;
public OutputStream out = null;
private static final long serialVersionUID = 1L;
/**new File(upload), dir 上传路径, map.get("id"))文件名
* 保存文件到服务器
* @Description
* @Author iechenyb
* @Date 2013-11-4 上午10:49:21
* @param upload 写入文件
* @param path 存储路径
* @param filename 上传文件名
* @throws IOException
* @ModHistory
*/
public static void saveFileFromInputStream(File upload,String path,String filename) throws IOException
{
try {
in = new BufferedInputStream(new FileInputStream(upload));
out = new BufferedOutputStream(new FileOutputStream(path + "/"+ filename));//文件名无后缀
byte[] buffer = new byte[BUFFER_SIZE];
int byteread = 0;
while ((byteread = in.read(buffer)) != -1) {
out.write(buffer, 0, byteread);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
in.close();
out.close();
}
}
//文件不存在时下载缺省文件
public static void downDefault(HttpServletResponse res) throws Exception{
String path=PathUtil.getPathInfo("UPLOAD_FILE_PATH")+"/default.txt";
File file = new File(path);
if(!file.exists()){//缺省的文件不存在创建并写入内容
file.createNewFile();
FileWriter w = new FileWriter(file);
w.write("您要下载的文件不存在!请与管理员联系?");
w.close();
}
String name=new String(("文件不存在.txt").getBytes("GBK"),"ISO-8859-1");
downFile(name , path, res);
}
/**
* Map : name显示文件名 String
* path 绝对全路径 String
* res response
* in 备选,文件输入流 FileInputStream
* @Author tangyunan
* @Date 2014-1-23 下午6:08:30
* @Description
* @param m
* @throws Exception
* @ModHistory
*
*/
public static void downFile(Map m,HttpServletResponse res) throws Exception{
String name =m.get("name")+"";
FileInputStream in=null;
String path="";
if(m.containsKey("in")){
in=(FileInputStream)m.get("in");
}
if(m.containsKey("path")){
path=m.get("path")+"";
}
if("".equals(path)&&in==null){
downDefault(res);
}else if(!"".equals(path)){
downFile(name,path,res);
}else {
dowStream(name,in,res);
}
}
//将制定路径的文件写出
public static void downFile(String name,String path,HttpServletResponse res) throws Exception{
FileInputStream in=null;
try{
in = new FileInputStream(new File(path));
}catch (Exception e){
downDefault(res);//下载缺省的文件
return ;
}
dowStream(name , in, res);
}
//将文件流in写出
public static void dowStream(String name,FileInputStream in,HttpServletResponse res) throws Exception{
OutputStream os = res.getOutputStream();
res.setHeader("Content-disposition", "attachment;filename="+name);
int b;
while ((b = in.read()) != -1) {
os.write(b);
}
in.close();
os.close();
}
}
文件处理工具(上传和下载)
最新推荐文章于 2022-06-26 17:29:10 发布