Java文件處理工具大全
作爲一個編程愛好者,把我珍藏使用已久的文件工具類拿出來分享分享。
包含
- 文件名處理:格式化文件名、獲取文件後綴、獲取無後綴文件名、文件歸組
- 文件大小處理:獲取文件大小
- 文件(圖片)寬高處理:獲取圖片文件尺寸
- 項目位置處理:獲取當前項目位置
- 文件類型判斷:文件類型判定
- 文件流:文件流轉換
用途
- 本地文件分組歸類
- 本地項目自動識別項目地址無需手動規定
- 非文件池包含文件限定
測試效果(我的個人博客實測)
代碼
package com.JavaUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
/**
* @author longxin
* @title: FileUtil
* @projectName com.JavaUtils
* @description: /
* @date 2020/3/6 0006 10:22
*/
public class FileUtil {
/**
* 文件後綴屬性池
*/
private static String [] files = {"docx", "doc", "wps", "txt",
"jpg", "gif", "png", "jpeg", "svg", "psd",
"exe", "apk",
"zip", "rar", "7z", "jar",
"css", "js", "java", "c", "cpp", "php", "py", "html",
"mp3", "mp4"
};
/**
* 文件後綴屬性類別池
*/
//文本類
private static String [] fileWord = {"docx", "doc", "wps", "txt"};
//圖片類
private static String [] fileImage = {"jpg", "gif", "png", "jpeg", "svg", "psd"};
//軟件類
private static String [] fileApp = {"exe", "apk"};
//壓縮包類
private static String [] filePress = {"zip", "rar", "7z", "jar"};
//代碼文件類
private static String [] fileCode = {"css", "js", "java", "c", "cpp", "php", "py", "html"};
//音影類
private static String [] fileLip = {"mp3", "mp4"};
//屬性池類屬性可根據需求自行增減,這裏可能羅列補全
/**
* MultipartFile轉File
* @param file
* @return
*/
public static File getFile(MultipartFile file) throws Exception{
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
return toFile;
}
/**
* 獲取流文件
* @param ins
* @param file
*/
private static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取當前項目文件的位置 - 適用大部分開發場景
* @return
*/
public static String getUplodFilePath() {
String path = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
path = path.substring(1, path.length());
try {
path = java.net.URLDecoder.decode(path, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int lastIndex = path.lastIndexOf("/") + 1;
path = path.substring(0, lastIndex);
File file = new File("");
return file.getAbsolutePath() + "/";
}
/**
* 獲取當前項目文件的位置 - 本地快速開發方便
* @return
*/
public static String getPorjectPath(){
String nowpath = "";
nowpath=System.getProperty("user.dir")+"/";
return nowpath;
}
/**
* 根據全文件名獲取文件名的後綴
* @param fileName
* @return
*/
public static String getFileExName(String fileName){
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
/**
* 獲取不帶後綴的文件名
* @param filename
* @return
*/
public static String getFileNameNoEx(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot >-1) && (dot < (filename.length()))) {
return filename.substring(0, dot);
}
}
return filename;
}
/**
* 轉換文件大小
* @param file
* @return
*/
public static String parseSize(File file) {
long size = file.length();
if (size < 1024) {
return String.valueOf(size) + "B";
} else {
size = size / 1024;
}
if (size < 1024) {
return String.valueOf(size) + "KB";
} else {
size = size / 1024;
}
if (size < 1024) {
size = size * 100;
return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "MB";
} else {
size = size * 100 / 1024;
return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "GB";
}
}
/**
* 獲取文件長和寬 (當文件爲圖片時)
* @param file file
* @return String
*/
public static String getImageWh(File file) {
try {
if(isAllowFile(file, fileImage)){
BufferedImage image = ImageIO.read(new FileInputStream(file));
return image.getWidth() + "x" + image.getHeight();
}
return "非圖片文件";
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 判斷文件類型是否符合指定文件類型池的類型
* @param file
* @param allowFileType
* @return
*/
public static boolean isAllowFile(File file, String[] allowFileType){
String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
return strIsArray(suffix, allowFileType);
}
/**
* 根據文件名生成更規範的文件名
* @param name 文件名
* @param prefix 文件組名(將會拼接到文件名前,便於文件分組)
* @return
*/
public static String getFileKey(String name, String prefix) {
if(prefix == null || prefix.equals("")){
prefix = "file"; //自定義前綴- 一般用於文件分組
}
Date date = new Date();
String d = date.getTime() + "";
if (!new File(getUplodFilePath() + prefix).exists()) {
new File(getUplodFilePath() + prefix).mkdirs();
}
name = StringUtils.trimToNull(name);
if (name == null) { //文件名爲空時,根據當前時間自動生成
return prefix + "-" + d.substring(9) + "-" + getSerialNo(2) + "." + null;
} else {
name = formatFileName(name);
String ext = getFileExName(name);
return prefix + "-"+ ext + getFileNameNoEx(name) + "-" + getSerialNo(2) + "." + (ext == null ? null : (ext));
}
}
/**
* 格式化文件名
* @param fileName
* @return
*/
public static String formatFileName(String fileName){
//如果文件名包含路徑,去掉路徑
fileName = fileName.replace('\\', '/');
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
return fileName;
}
/////////////以下方法可移至StringUtil中,這裏爲了大家能直接調用,將其放在代碼尾///////////
/**
* 字符池
*/
public static char[] serialNo = {'1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N','P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z' };
/**
* 判斷字符串數組arr內是否包含字符串str
* @param str
* @param arr
* @return
*/
public static boolean strIsArray(String str, String [] arr){
return Arrays.asList(arr).contains(str);
}
/**
* 獲取指定位數的隨機字符串 - 從自定字符池中獲取
* @param size
* @return
*/
public static String getSerialNo(int size) {
Random random = new Random();
char[] cs = new char[size];
for (int i = 0; i < cs.length; i++) {
cs[i] = serialNo[random.nextInt(serialNo.length)];
}
return new String(cs);
}
}
感謝查看