<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
package com.tanhua.common.utils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import java.util.List;
/**
* 文件名封装处理工具类
* <dependency>
* <groupId>joda-time</groupId>
* <artifactId>joda-time</artifactId>
* </dependency>
*
* <dependency>
* <groupId>org.apache.commons</groupId>
* <artifactId>commons-lang3</artifactId>
* </dependency>
*/
public class FileUtils {
private FileUtils() {
}
/*
* 测试main 方法。无实际业务应用
* 生成的文件名: images/2021/07/22/16269213666967476.jpg
*/
public static void main(String[] args) {
String filePath = getFilePath("9527.jpg");
System.out.println(filePath);
}
/**
* 文件新路径,cos桶对象。名,和文件路径。用原始文件名,拼接日期。做路径,当前时间毫秒。做文件名
* image+年+月+日+时间毫秒+文件名后缀
*
* @param sourceFileName 原始文件名
* @return images/2021/07/22/16269213666967476.jpg
*/
public static String getFilePath(String sourceFileName) {
DateTime dateTime = new DateTime();
return "images/" + dateTime.toString("yyyy")
+ "/" + dateTime.toString("MM") + "/"
+ dateTime.toString("dd") + "/" + System.currentTimeMillis() +
RandomUtils.nextInt(100, 9999) + "." +
StringUtils.substringAfterLast(sourceFileName, ".");
}
/**
* 图片做校验,对后缀名 效验, 忽略大小写
*
* @param fileNames .jpg .jpeg List<String>文件后缀集合
* @param fileName 完整文件名
* @return 存在返回true 不存在返回false
*/
public static boolean isFileSuffix(List<String> fileNames, String fileName) {
for (String name : fileNames) {
if (StringUtils.endsWithIgnoreCase(fileName, name)) {
return true;
}
}
return false;
}
}