文件操作java源码

package ds.sw.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		String method = request.getParameter("method");
		
		if(method.equals("upload")){
			upload(request,response);
		}else if(method.equals("listfile")){
			listAll(request,response);
		}else if(method.equals("listMuban")){
			listMuban(request,response);
		}else if(method.equals("download")){
			download(request,response);
		}else if(method.equals("downloadM")){
			downloadM(request,response);
		}else if(method.equals("delete")){
			delete(request,response);
		}else if(method.equals("deleteM")){
			deleteM(request,response);
		}else{
			request.getRequestDispatcher("/back/error.jsp");
		}

	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
	
	@SuppressWarnings("rawtypes")
	public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
			{
		
		//限定文件类型
			List types = Arrays.asList("doc","docx","zip","rar");
		
			//创建磁盘工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024*1024*5);//设置缓存区大小为5M
			factory.setRepository(new File(this.getServletContext().getRealPath("/WEB-INF/file/temp")));//设置缓存区文件夹所在目录为当前项目下的temp文件夹
			
			//创建解析器
			ServletFileUpload jiexiqi = new ServletFileUpload(factory);
			jiexiqi.setHeaderEncoding("utf-8");//设置文件名的编码方式
		
		//限定文件大小
			jiexiqi.setSizeMax(1024*1024*5);//设置上传文件的最大值不能超过5M
			try {//解析完成后生成一个文件项目列表list
				List<FileItem> list = jiexiqi.parseRequest(request);
				for(FileItem item:list){
					if(item.isFormField()){
						//为普通输入项
						String inputName = item.getFieldName();
						String inputValue = item.getString("utf-8");//设置输入项编码方式
						System.out.println(inputName + "=" +inputValue);
					}else{
						//代表item封装的是上传文件
						String filename = item.getName().substring(item.getName().lastIndexOf("\\")+1);//获取文件名
						if(filename.equals(null)||filename.trim().equals("")){
							request.setAttribute("message","你还没选择上传文件,请反回重新选择上传的文件!");
							request.getRequestDispatcher("/back/message.jsp").forward(request, response);
							return;
						}
						
				//限定文件上传了类型
						String ext = filename.substring((filename.lastIndexOf(".")+1));    //获得文件扩展名
						if(!types.contains(ext)){
							request.setAttribute("message","本系统不支持 ."+ext+" 格式的文件上传!");
							request.getRequestDispatcher("/back/message.jsp").forward(request, response);
							return;
						}
						
						
						InputStream in =item.getInputStream();
						int len = 0;
						byte buffer[] =new byte[1024];
						
						String savepath = this.getServletContext().getRealPath("/WEB-INF/file/download");
						String saveFileName = uniqueFileName(filename);
						FileOutputStream out = new FileOutputStream(savepath+File.separator +saveFileName);//File.separator用于生成分隔符,避免操作系统误判
						while((len = in.read(buffer))>0){													
							out.write(buffer, 0, len);
						}
						in.close();
						out.close();
						item.delete();//删除缓存区临时文件
					}
					 
				}
			
			}catch(FileUploadBase.SizeLimitExceededException e1){
				request.setAttribute("message","上传文件大小不能超过5M");
				request.getRequestDispatcher("/back/message.jsp").forward(request, response);
				
	
				return;
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			
			request.setAttribute("message","你的文件已经上传成功!");
			request.getRequestDispatcher("/back/message.jsp").forward(request, response);
		
	
	}

	@SuppressWarnings("rawtypes")
	public void listAll(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String path = this.getServletContext().getRealPath("/WEB-INF/file/upload");
		Map map = new HashMap();
		listfile(new File(path),map);
		request.setAttribute("map",map);
		request.getRequestDispatcher("/back/listfile.jsp").forward(request, response);
	}
	@SuppressWarnings("rawtypes")
	public void listMuban(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String path = this.getServletContext().getRealPath("/WEB-INF/file/download");
		Map map = new HashMap();
		listfile(new File(path),map);
		request.setAttribute("map",map);
		request.getRequestDispatcher("/back/listMuban.jsp").forward(request, response);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void listfile(File file,Map map){
		if(!file.isFile()){
			File children[] = file.listFiles();
			for(File f : children){
				listfile(f, map);
			}
		}else{
			String filename = file.getName().substring(file.getName().indexOf("_")+1);
			map.put(file.getName(),filename); 
		}
	}

	public void download(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 得到要下载的文件名 uuid
		String filename = request.getParameter("filename");
		filename = new String(filename.getBytes("iso8859-1"), "UTF-8");
		// 找出这个文件 url c:\\
		String path = this.getServletContext().getRealPath("/WEB-INF/file/upload") ;

		File file = new File(path + File.separator +filename);
		if (!file.exists()) {
			request.setAttribute("message", "对不起,您要下载的资源已被删除");
			request.getRequestDispatcher("/back/message.jsp").forward(request,
					response);
			return;
		}
		// 得到文件的原始文件名
		String oldname = file.getName().substring(
				file.getName().indexOf("_") + 1);
		// 通知浏览器以下载方式打开下面发送的数据
		response.setHeader("content-disposition", "attachment;filename="
				+ URLEncoder.encode(oldname, "UTF-8"));
		FileInputStream in = new FileInputStream(file);
		int len = 0;
		byte buffer[] = new byte[1024];
		OutputStream out = response.getOutputStream();
		while ((len = in.read(buffer)) > 0) {
			out.write(buffer, 0, len);
		}
		in.close();

	}

	public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
				// 得到要下载的文件名 uuid
				String filename = request.getParameter("filename");
				filename = new String(filename.getBytes("iso8859-1"), "UTF-8");
				// 找出这个文件 url c:\\
				String path = this.getServletContext().getRealPath("/WEB-INF/file/upload") ;

				File file = new File(path + File.separator +filename);
				if (!file.exists()) {
					request.setAttribute("message", "对不起,您要删除的资源不存在");
					request.getRequestDispatcher("/back/message.jsp").forward(request,
							response);
				}else {
					file.delete();
					request.setAttribute("message", filename.substring(filename.lastIndexOf("_")+1)+"已被成功删除!");
					request.getRequestDispatcher("/back/message.jsp").forward(request,
							response);
				}
	}

	public void downloadM(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 得到要下载的文件名 uuid
		String filename = request.getParameter("filename");
		filename = new String(filename.getBytes("iso8859-1"), "UTF-8");
		// 找出这个文件 url c:\\
		String path = this.getServletContext().getRealPath("/WEB-INF/file/download") ;

		File file = new File(path + File.separator +filename);
		if (!file.exists()) {
			request.setAttribute("message", "对不起,您要下载的资源已被删除");
			request.getRequestDispatcher("/back/message.jsp").forward(request,
					response);
			return;
		}
		// 得到文件的原始文件名
		String oldname = file.getName().substring(
				file.getName().indexOf("_") + 1);
		// 通知浏览器以下载方式打开下面发送的数据
		response.setHeader("content-disposition", "attachment;filename="
				+ URLEncoder.encode(oldname, "UTF-8"));
		FileInputStream in = new FileInputStream(file);
		int len = 0;
		byte buffer[] = new byte[1024];
		OutputStream out = response.getOutputStream();
		while ((len = in.read(buffer)) > 0) {
			out.write(buffer, 0, len);
		}
		in.close();

	}

	public void deleteM(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
				// 得到要下载的文件名 uuid
				String filename = request.getParameter("filename");
				filename = new String(filename.getBytes("iso8859-1"), "UTF-8");
				// 找出这个文件 url c:\\
				String path = this.getServletContext().getRealPath("/WEB-INF/file/download") ;

				File file = new File(path + File.separator +filename);
				if (!file.exists()) {
					request.setAttribute("message", "对不起,您要删除的资源不存在");
					request.getRequestDispatcher("/back/message.jsp").forward(request,
							response);
				}else {
					file.delete();
					request.setAttribute("message", filename.substring(filename.lastIndexOf("_")+1)+"已被成功删除!");
					request.getRequestDispatcher("/back/message.jsp").forward(request,
							response);
				}
	}

	public  String uniqueFileName(String filename){
		//该方法用于生成唯一文件名,避免文件被覆盖掉
		return UUID.randomUUID().toString()+"_"+filename;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值