JAVA 工具类 文件工具类

package com.thinkgem.jeesite.modules.meeting.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.Exceptions;

/**
 * 
 * <p>Title: FileUtil</p>
 * <p>Description: 文件工具类</p>
 * <p>Company: </p> 
 * @Package com.meeting.attachment.utils
 * @author chenlf
 * @date 2020年1月14日 上午10:55:08
 * @version lsmeeting-1.0
 */
public class FileUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
	
	public static final String UPLOAD_PATH = Global.getConfig("uploadPath");
	
	/**
	 * 是否上传了文件 
	 * @param files
	 * @return
	 */
	public static Boolean isUploadFile(MultipartFile[] files) {
		boolean isUpload = false;
		for (MultipartFile file : files) {
			if (StringUtils.isNotBlank(file.getOriginalFilename())) {
				isUpload = true;
				break;
			}
		}
		return isUpload;
	}
	
	/**
	 * 保存附件
	 * @title saveFile
	 * @Description 描述方法做什么用
	 * @param is       文件流
	 * @param savePath 保存路径(不包含根路径)
	 * @return
	 */
	public static Boolean saveFile(InputStream is,String savePath)throws IOException{
		OutputStream os = null;
		try{
			String rootPath = UPLOAD_PATH+File.separator+savePath.substring(0, savePath.lastIndexOf(File.separator)-1);
			String fileName = savePath.substring(savePath.lastIndexOf(File.separator));
			File saveDir = new File(rootPath);
			if(!saveDir.exists()){
				saveDir.mkdirs();//创建文件夹
			}
			os = new FileOutputStream(rootPath+File.separator+fileName);//奇怪为什么直接拼savePath路径不能写文件,报错找不到文件,为什么折开正常
			byte[] b = new byte[100*1024];  
			int bytesRead = 0;
			while ((bytesRead = is.read(b)) != -1) {  
			    os.write(b, 0, bytesRead);  
			}
			return true;
		}finally{
			try{
				os.close();
				is.close();
			}catch(Exception ex){
				Exceptions.unchecked(ex);
			}
		}
	}

	/**
	 * 上传单个文件
	 * @param multipartFile
	 * @param uploadPath
	 */
	public static String upload(MultipartFile multipartFile, String uploadPath) {
		String originalFilename = multipartFile.getOriginalFilename();
		logger.debug("开始上传文件:" + originalFilename);
		String fileName = getSaveFileName(originalFilename);
		File dir = new File(uploadPath);
		File file = new File(uploadPath, fileName);
		try {
			if (!dir.exists()) {
				dir.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			multipartFile.transferTo(file);
			logger.debug(uploadPath + File.separator + originalFilename + "\t上传成功,保存为:" + fileName);
			//返回相对路径
			return transformRelativePath(UPLOAD_PATH, file.getPath());
		} catch (IOException e) {
			logger.debug(originalFilename + "上传失败!");
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 
	 * @title upload
	 * @Description 多文件上传
	 * @author chenlf
	 * @param multipartFiles
	 * @param uploadPath
	 */
	public static void upload(MultipartFile[] multipartFiles, String uploadPath) {
		for(int i = 0; i < multipartFiles.length; i ++) {
			upload(multipartFiles[0], uploadPath);
		}
	}
	
	/**
	 * 
	 * @title getFileUploadPath
	 * @Description 附件上传
	 * @author chenlf
	 * @param bsId
	 * @return 类型/业务ID/时间
	 */
	public static String getFileUploadPath(String bsId, String type){
		String uploadPath = UPLOAD_PATH;
		DateFormat format=new SimpleDateFormat("yyyyMMdd");
		String date = format.format(new Date());
		if (StringUtils.isNotBlank(bsId)) {
			uploadPath += File.separator + type +File.separator + bsId + File.separator + date;
		} else {
			uploadPath += File.separator + type +File.separator + date;
		}
		logger.debug("上传路径:" + uploadPath);
		return uploadPath;
	}
	
	/**
	 * 相对路径转绝对路径
	 * @title transformAbsolutePath
	 * @Description 描述方法做什么用
	 * @param relativePath 相对路径
	 * @return
	 */
	public static String transformAbsolutePath(String relativePath){
		if (StringUtils.isNotBlank(relativePath)) {
			//得到配置文件绝对路径
			String absolutePath = UPLOAD_PATH+relativePath;
			return absolutePath;
		}
		return "";
	}
	
	/**
	 * 根据配置路径和保存路径截取绝对路径
	 * @title transformRelativePath
	 * @Description 描述方法做什么用
	 * @param propertiesPath 配置路径
	 * @param savePath 保存路径
	 * @return
	 */
	public static String transformRelativePath(String propertiesPath, String savePath){
		if (StringUtils.isNotBlank(propertiesPath) && StringUtils.isNotBlank(savePath)) {
			//截取得到绝对路径
			propertiesPath = new File(propertiesPath).getPath().replace("//", File.separator);
			String relativePath = savePath.replace(propertiesPath, "");
			return relativePath;
		}
		return "";
	}
	
	/**
	 * 拼接保存路径以及设置文件唯一名称
	 * @title getSaveFileName
	 * @Description 描述方法做什么用
	 * @param fileName
	 * @return
	 */
	private static String getSaveFileName(String fileName) {
		StringBuffer savaFileName = new StringBuffer();
		savaFileName.append(System.currentTimeMillis());
		savaFileName.append(fileName.substring(fileName.lastIndexOf(".")));
		return savaFileName.toString();
	}
	
	/**
	 * 下附件以及预览
	 * @title downLoad
	 * @Description 下附件以及预览
	 * @param response
	 * @param fileName
	 * @param filePath
	 * @param fileType
	 * @return
	 */
	public static void downLoad(HttpServletResponse response,String fileName, 
			String filePath, FileType fileType) {
		filePath = transformAbsolutePath(filePath);
		String contentType;
		switch (fileType) {
			case jpg :
			case png :
			case jpeg :
				contentType = "image/*";
				break;
			case doc :
			case docx:
				contentType = "application/msword";
			default :
				contentType = "multipart/form-data";
				break;
		}
		InputStream inputStream = null;
		OutputStream os = null;
		try {
			response.setCharacterEncoding("utf-8");
			if (!StringUtils.isNotBlank(contentType)) {
				response.setContentType(contentType);
			}
			response.setHeader("Content-Disposition", "attachment;fileName="
					+ new String(fileName.getBytes("gbk"),"iso-8859-1"));
			File file = new File(filePath);
			//先判断文件是否存在
			if (file.exists()) {
				File targetFile = new File(filePath);
				inputStream = new FileInputStream(targetFile);
				os = response.getOutputStream();
				byte[] b = new byte[2048];
				int length;
				while ((length = inputStream.read(b)) > 0) {
					os.write(b, 0, length);
				}
			}
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 根据文件路径删除文件
	 * @title deleteFile
	 * @Description 描述方法做什么用
	 * @param filePath 文件绝对路径
	 * @return
	 */
	public static boolean deleteFile(String filePath){
		filePath = transformAbsolutePath(filePath);
		File file = new File(filePath);
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
            	logger.debug("删除文件" + filePath + "成功!");
                return true;
            } else {
            	logger.debug("删除文件" + filePath + "失败!");
                return false;
            }
        } else {
        	logger.debug("文件不存在!");
            return false;
        }
	}
	
	/**
	 * @title readByte
	 * @Description 读取文件(拿到相对路径转绝对路径)
	 * @param filePath
	 * @return
	 */
	public static byte[] readByte(String filePath) {
		filePath = transformAbsolutePath(filePath);
		return readByteFilePath(filePath);
	}
	
	/**
	 * @title readBytes
	 * @Description 根据路径读取文件
	 * @param filePath
	 * @return
	 */
	public static byte[] readByteFilePath(String filePath) {
		FileInputStream fis;
		try {
			fis = new FileInputStream(filePath);
			try {
				byte r[] = new byte[fis.available()];
				fis.read(r);
				return r;
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			logger.debug("文件不存在!");
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * @title getSystemAccessPath
	 * @Description 获取系统访问路径(协议名://IP地址:端口号/系统名)
	 * @param request
	 */
	public static String getSystemAccessPath(HttpServletRequest request) {
		return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
	}
	
}
package com.thinkgem.jeesite.modules.meeting.utils;

/**
 * 
 * <p>Title: FileType</p>
 * <p>Description: 文件类型</p>
 * <p>Company: </p> 
 * @Package com.meeting.attachment.utils
 * @author chenlf
 * @date 2020年1月14日 上午10:41:50
 * @version lsmeeting-1.0
 */
public enum FileType {
	doc,
	docx,
	xls,
	xlsx,
	pdf,
	jpg,
	png,
	jpeg,
	other;//其他
	
	@Override
	public String toString() {
		return this.name();
	}

	public static FileType create(String value) {
		try {
			return FileType.valueOf(value);
		} catch (Exception e) {
			return FileType.other;
		}
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值