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;
		}
	}
	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章