Spring 文件操作

原创 2017年01月03日 09:29:50
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fhzz.business.valueObject.CFileInfor;
import com.fhzz.core.util.FileUtils;

public class FileOperateUtil {

	private static Log log = LogFactory.getLog(FileOperateUtil.class);

	public static final String UPLOADDIR = "uploaddir/";

	/**
	 * 多文件上传
	 * 
	 * @param request
	 * @param fileName form表单中file的name
	 * @return 返回上传成功文件列表
	 * @throws Exception
	 */
	public static List<File> uploadFiles(HttpServletRequest request, String fileName) throws Exception {
		return upload(request, fileName, filePath(request));
	}

	/**
	 * 多文件上传
	 * 
	 * @param request
	 * @param fileName form表单中file的name
	 * @param path 上传指定的路径
	 * @return 返回上传成功文件列表
	 */
	public static List<File> upload(HttpServletRequest request, String fileName, String path) {
		List<File> mfs = new ArrayList<File>();

		if (!(request instanceof MultipartHttpServletRequest)) {
			String errorMsg = "your post form is not support ENCTYPE='multipart/form-data' ";
			log.error(errorMsg);
			throw new RuntimeException(errorMsg);
		}

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> multipartFiles = multipartRequest.getFiles(fileName);

		if (null != multipartFiles && multipartFiles.size() > 0) {
			for (MultipartFile mf : multipartFiles) {
				if (mf.getSize() <= 0)
					continue;

				createFile(path);
				DateFormat t = new SimpleDateFormat("yyyyMMddHHmmss");
				Date date = new Date();
				String name = t.format(date);

				char[] realName = mf.getOriginalFilename().toCharArray();
				int i = 0;
				for (i = 0; i < realName.length; i++) {
					if (realName[i] == '.')
						break;
				}
				String realPath = path + File.separator + name;
				File source = new File(realPath);
				try {
					mf.transferTo(source);
					mfs.add(source);

					log.debug("Upload file " + source.getAbsoluteFile() + " Success!");
				} catch (Exception e) {
					String errorMsg = "Upload file " + source.getAbsoluteFile() + " Error!" + e.getMessage();
					log.error(errorMsg);
					throw new RuntimeException(errorMsg);
				}
			}
		}
		return mfs;
	}
	
	/**
	 * 多文件上传(指定文件夹,保留文件名)
	 * @param request
	 * @param fileName
	 * @param path
	 * @return
	 */
	public static List<File> uploadWithFileName(HttpServletRequest request, String fieldName, String fileDir) {
		List<File> mfs = new ArrayList<File>();

		if (!(request instanceof MultipartHttpServletRequest)) {
			String errorMsg = "your post form is not support ENCTYPE='multipart/form-data' ";
			log.error(errorMsg);
			throw new RuntimeException(errorMsg);
		}

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> multipartFiles = multipartRequest.getFiles(fieldName);

		if (null != multipartFiles && multipartFiles.size() > 0) {
			for (MultipartFile mf : multipartFiles) {
				if (mf.getSize() <= 0)
					continue;


				String fileName = mf.getOriginalFilename();
				String realPath = StringUtils.mergeStringWithSeparator(fileDir,fileName);
				File source = new File(realPath);
				try {
					mf.transferTo(source);
					mfs.add(source);

					log.debug("Upload file " + source.getAbsoluteFile() + " Success!");
				} catch (Exception e) {
					String errorMsg = "Upload file " + source.getAbsoluteFile() + " Error!" + e.getMessage();
					log.error(errorMsg);
					throw new RuntimeException(errorMsg);
				}
			}
		}
		return mfs;
	}

	/**
	 * 多文件上传
	 * @param request
	 * @param fileName form表单中file的name
	 * @param path 上传指定的路径
	 * @return 返回上传成功文件列表
	 */
	@SuppressWarnings("unchecked")
	public static void uploadLocalFile(HttpServletRequest request, String fileName, String path, String randFlag) {
		if (!(request instanceof MultipartHttpServletRequest)) {
			String errorMsg = "your post form is not support ENCTYPE='multipart/form-data' ";
			log.error(errorMsg);
			throw new RuntimeException(errorMsg);
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> multipartFiles = multipartRequest.getFiles(fileName);
		if (null != multipartFiles && multipartFiles.size() > 0) {
			for (MultipartFile mf : multipartFiles) {
				if (mf.getSize() <= 0) {
					continue;
				}
				String realName = mf.getOriginalFilename();
				if (checkNameExists(realName, randFlag)) {
					return;
				}
				CFileInfor cfile = new CFileInfor();
				cfile.setFileName(StringUtils.replaceBlank(realName)); // 设置文件名
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				try {
					BufferedImage image = ImageIO.read(mf.getInputStream());
					String formatName = FileUtils.getFileSufix(StringUtils.replaceBlank(realName));
					//ImageIO.write(image, DEFAULT_TYPE, out);
					ImageIO.write(image, formatName, out);
					byte[] b = out.toByteArray();
					cfile.setFileStream(b); // 设置文件流
					cfile.setUploadTime(new Date());
					List list = StaticValues.cacheUploadFileStream.get(randFlag);
					if (list == null || list.size() == 0) {
						list = new ArrayList();
						list.add(System.currentTimeMillis()); // 将当前时间放入
					}
					list.add(cfile);
					StaticValues.cacheUploadFileStream.put(randFlag, list);
				} catch (Exception e) {
					String errorMsg = "Upload file Error!" + e.getMessage();
					log.error(errorMsg);
					throw new RuntimeException(errorMsg);
				} finally {
					if (out != null) {
						try {
							out.close();
							out = null;
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

	/**
	 * 检验文件名是否存在
	 * 
	 * @param name
	 */
	@SuppressWarnings("unchecked")
	public static boolean checkNameExists(String fileName, String randFlag) {
		CFileInfor cfile = null;
		List list = StaticValues.cacheUploadFileStream.get(randFlag);
		if (list != null && list.size() > 1) {
			for (int i = 1; i < list.size(); i++) {
				cfile = (CFileInfor) list.get(i);
				if (cfile != null && fileName.equals(cfile.getFileName())) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 文件下载 , 根据文件名下载文件
	 * 
	 * @param request
	 * @param response
	 * @param fileName
	 *            文件名
	 * @throws Exception
	 */
	public static void download(HttpServletRequest request, HttpServletResponse response, String filePath, String fileName) throws Exception {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		String downLoadPath = filePath + fileName;

		response.setCharacterEncoding("ISO8859-1");
		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));

		File f = new File(downLoadPath);
		if (!f.exists())
			throw new RuntimeException("Download file not exists! file = " + downLoadPath);

		try {
			bis = new BufferedInputStream(new FileInputStream(f));
			bos = new BufferedOutputStream(response.getOutputStream());

			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}

			log.debug("Download file " + downLoadPath + " Success!");
		} catch (Exception e) {
			String errorMsg = "Download file " + downLoadPath + " Error!  " + e.getMessage();
			log.error(errorMsg);
			throw new RuntimeException(errorMsg);
		} finally {
			if (null != bis)
				bis.close();
			if (null != bos)
				bos.close();
			bis = null;
			bos = null;
		}
	}

	/**
	 * 文件上传 存储目录 临时目录
	 * 
	 * @param request
	 * @return
	 */
	public static String filePath(HttpServletRequest request) {
		String ctxPath = request.getSession().getServletContext().getRealPath("/");
		String filePath = ctxPath + FileOperateUtil.UPLOADDIR;
		return filePath;
	}

	/**
	 * 上传路径检查,不存在则创建指定文件夹
	 * 
	 * @param filePath
	 */
	public static void createFile(String filePath) {
		try {
			File f = new File(filePath);
			if (!f.exists()) {
				f.mkdir();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解析出上传文件的文件名 杨朝晖 2012.09.07
	 * 
	 * @param request
	 * @return 上传是否成功
	 * @throws Exception
	 */
	public static String extractFileName(HttpServletRequest request, String Filedata) throws Exception {
		String realPath = "";
		if (!(request instanceof MultipartHttpServletRequest)) {
			String errorMsg = "your post form is not support ENCTYPE='multipart/form-data' ";
			log.error(errorMsg);
			realPath = "";
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> multipartFiles = multipartRequest.getFiles(Filedata);
		if (null != multipartFiles && multipartFiles.size() > 0) {
			MultipartFile mf = multipartFiles.get(0);
			realPath = mf.getOriginalFilename();
		}
		return realPath;
	}

	/**
	 * 文件上传(指定文件保存路径和文件名) 杨朝晖 2012.09.07
	 * 
	 * @param request
	 * @return 上传是否成功
	 * @throws Exception
	 */
	public static File uploadFilesSpecifyFileNameAndPath(HttpServletRequest request, String filePathWithFileName, String Filedata) throws Exception {
		MultipartFile mf = null;
		File mff = null;
		if (!(request instanceof MultipartHttpServletRequest)) {
			String errorMsg = "your post form is not support ENCTYPE='multipart/form-data' ";
			log.error(errorMsg);

			throw new RuntimeException(errorMsg);
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> multipartFiles = multipartRequest.getFiles(Filedata);
		if (null != multipartFiles && multipartFiles.size() > 0) {
			mf = multipartFiles.get(0);
			String realPath = StringUtils.mergeStringWithSeparator(filePathWithFileName,mf.getOriginalFilename());
//			String realPath = filePathWithFileName;
			File source = new File(realPath);
			try {
				mf.transferTo(source);
				mff = source;
				log.debug("Upload file " + source.getAbsoluteFile() + " Success!");
			} catch (Exception e) {
				String errorMsg = "Upload file " + source.getAbsoluteFile() + " Error!" + e.getMessage();
				log.error(errorMsg);
				throw new RuntimeException(errorMsg);

			}
		}
		return mff;
	}
	
	/**
	 * 文件上传(指定文件夹,保留文件名)
	 * @param request
	 * @param fileDir 指定文件夹
	 * @param Filedata 
	 * @return
	 * @throws Exception
	 */
	public static File uploadFilesSpecifyPath(HttpServletRequest request, String fileDir, String Filedata) throws Exception {
		MultipartFile mf = null;
		File mff = null;
		if (!(request instanceof MultipartHttpServletRequest)) {
			String errorMsg = "your post form is not support ENCTYPE='multipart/form-data' ";
			log.error(errorMsg);

			throw new RuntimeException(errorMsg);
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> multipartFiles = multipartRequest.getFiles(Filedata);
		if (null != multipartFiles && multipartFiles.size() > 0) {
			mf = multipartFiles.get(0);
			String realPath = StringUtils.mergeStringWithSeparator(fileDir,mf.getOriginalFilename());
			File source = new File(realPath);
			try {
				mf.transferTo(source);
				mff = source;
				log.debug("Upload file " + source.getAbsoluteFile() + " Success!");
			} catch (Exception e) {
				String errorMsg = "Upload file " + source.getAbsoluteFile() + " Error!" + e.getMessage();
				log.error(errorMsg);
				throw new RuntimeException(errorMsg);

			}
		}
		return mff;
	}

	/**
	 * 删除目录或文件 陈子雅 2013.06.18
	 * @param sPath
	 * @return
	 */
	public static boolean deleteFolder(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 判断目录或文件是否存在
		if (!file.exists()) { // 不存在返回 false
			return flag;
		} else {
			// 判断是否为文件
			if (file.isFile()) { // 为文件时调用删除文件方法
				return deleteFile(sPath);
			} else { // 为目录时调用删除目录方法
				return deleteDirectory(sPath);
			}
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param sPath
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true,否则返回false
	 */
	public static boolean deleteFile(String sPath) {
		try {
			boolean flag = false;
			File file = new File(sPath);
			// 路径为文件且不为空则进行删除
			if (file.isFile() && file.exists()) {
				file.delete();
				flag = true;
			}
			return flag;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 删除目录(文件夹)以及目录下的文件
	 * 
	 * @param sPath
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true,否则返回false
	 */
	public static boolean deleteDirectory(String sPath) {
		// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在,或者不是一个目录,则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				// 删除子文件
				if (files[i].isFile()) {
					flag = deleteFile(files[i].getAbsolutePath());
					if (!flag)
						break;
				} // 删除子目录
				else {
					flag = deleteDirectory(files[i].getAbsolutePath());
					if (!flag)
						break;
				}
			}
		}
		if (!flag)
			return false;
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 获取文件大小
	 * @param file
	 * @return
	 */
	public static float getFileSize(File file){
		float length = file.length();
		String format = new DecimalFormat("0.0").format(length/1048576f);
		return Float.parseFloat(format);
	}

	/**
	 * 删除目录下的文件
	 * @param appImageDir
	 */
	public static void deleteFilesInFloder(String sPath) {
		// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在,或者不是一个目录,则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return ;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				// 删除子文件
				if (files[i].isFile()) {
					flag = deleteFile(files[i].getAbsolutePath());
					if (!flag)
						break;
				} // 删除子目录
				else {
					flag = deleteDirectory(files[i].getAbsolutePath());
					if (!flag)
						break;
				}
			}
		}
	}
}

版权声明:原创文章,转载请标明出处...

相关文章推荐

Spring(1)——文件资源操作

加载文件资源     Spring 定义了一个 org.springframework.core.io.Resource 接口,Resource 接口是为了统一各种类型不同的资源而定义的,Sprin...

spring工具 ---读文件

package com.wondersgroup.subject.common.util;import java.io.File;import java.io.FileReader;import ja...

Spring Batch 之 Sample(XML文件操作)(五)

The original website:http://www.cnblogs.com/gulvzhe/archive/2011/12/03/2274908.html 前篇关于Spring Batc...

Spring Batch 之 Sample(CSV文件操作)(四)

The real websit,let's respect the author:http://www.cnblogs.com/gulvzhe/archive/2011/11/06/2238125.h...

基于文件操作的留言系统

  • 2017年11月09日 23:05
  • 2KB
  • 下载

CSV文件操作

  • 2016年06月28日 16:47
  • 1KB
  • 下载

基本文件操作之常用命令和工具(vi、find)

基本文件操作之常用命令和工具 1、文件编辑工具 vi

Linux下的文件操作应用

  • 2015年05月16日 16:14
  • 545KB
  • 下载

文件操作和网络编程实验

  • 2015年05月10日 13:40
  • 37KB
  • 下载

Linux下的一些文件操作

Linux下的一些文件操作
  • K54387
  • K54387
  • 2017年10月18日 20:29
  • 44
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Spring 文件操作
举报原因:
原因补充:

(最多只允许输入30个字)