FileUtil.java 1.77 KB
package com.cjs.site.util.file;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

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

/**
 * 文件工具类
 * 
 * @author tongyufu
 *
 */
public class FileUtil {

	public static final String ENCODING = "UTF-8";
	
	/** 获取后缀名(包含.),如果没有后缀,返回"" @author trunks */
	public static String getSuffix(String filename) {
		if (StringUtils.isBlank(filename) || filename.indexOf(".") == -1) {
			return "";
		}
		return filename.substring(filename.lastIndexOf(".")).trim();
	}

	/**
	 * 移动文件到指定target
	 * 
	 * @param source
	 *            被移动文件
	 * @param target
	 *            目标路径
	 * @throws IOException
	 *             如果在service中调用,请在catch中 throw ServiceException,确保事务回滚
	 * @author trunks
	 */
	public static void transferFile(MultipartFile source, String target) throws IOException {
		File targetFile = new File(target);
		targetFile.getParentFile().mkdirs();
		source.transferTo(targetFile);
	}

	// 获得当前时间
	public static String QueryArticleImgPrefix() {
		String nowtime = new Date().getTime() + "";
		return nowtime;
	}

	/**
	 * 创建月份目录(单月前面补0)
	 * 
	 * @param parent 父路径
	 * @return 目录完整路径(以/结尾)
	 */
	public static String makeMonthDir(String parent) {
		String dir = "";
		Calendar calendar = Calendar.getInstance();
		int month = calendar.get(Calendar.MONTH) + 1;
		if (month < 10) {
			dir += "0";
		}
		dir += month;
		if (!parent.endsWith("/")) {
			parent += "/";
		}
		dir = parent + dir;
		File file = new File(dir);
		if (!file.exists()) {
			file.mkdirs();
		}
		return dir + "/";
	}

}