E1ED922C1E9526DD63272D7EC5C6CB77
2020-09-23 5c59454c8a12b1a19846c23c99cff612db037e4f
提交 | 用户 | age
5c5945 1 package com.hx.util;
E 2
3 import com.hx.exception.TipsException;
4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory;
6 import org.springframework.web.multipart.MultipartFile;
7
8 import java.io.*;
9 import java.text.SimpleDateFormat;
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.Date;
13 import java.util.List;
14
15 /** 文件处理工具
16  * @author ChenJiaHe
17  * @Date 2020-06-17
18  */
19 public class FileUtils {
20
21     private final static Logger logger = LoggerFactory.getLogger(FileUtils.class);
22
23     private static int BUFFER_SIZE = 1024;
24
25     /**
26      * @param path
27      * @MethodName fileIsExists
28      * @Description 文件是否存在
29      * @Author ChenJiaHe
30      * @Date 2019/9/7 9:13
31      * @Since JDK 1.8
32      */
33     public static boolean fileIsExists(String path) {
34         File file = new File(path);
35         if (file.exists()) {
36             return true;
37         } else {
38             return false;
39         }
40     }
41
42     /**
43      * @param sourceFile
44      * @param targetFile
45      * @MethodName copyFile
46      * @Description 复制文件
47      * @Author ChenJiaHe
48      * @Date 2019/9/7 9:36
49      * @Since JDK 1.8
50      */
51     public static void copyFile(File sourceFile, File targetFile) throws IOException {
52         BufferedInputStream inputStream = null;
53         BufferedOutputStream outputStream = null;
54         try {
55             inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
56             outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
57             byte[] b = new byte[BUFFER_SIZE];
58             int len;
59             while ((len = inputStream.read(b)) != -1) {
60                 outputStream.write(b, 0, len);
61             }
62             outputStream.flush();
63         } catch (Exception e) {
64             logger.error("copy file error", e);
65         } finally {
66             if (inputStream != null) {
67                 inputStream.close();
68             }
69             if (outputStream != null) {
70                 outputStream.close();
71             }
72         }
73     }
74
75     /**
76      * @param path
77      * @param fileType 文件类型,0 = 文件夹 1 = 文件
78      * @MethodName getAllFiles
79      * @Description 讀取文件夹下的,不包括子文件夹内
80      * @Author ChenJiaHe
81      * @Date 2019/9/17 15:56
82      * @Since JDK 1.8
83      */
84     public static List<String> getAllFiles(String path, String fileType) {
85         List<String> fileList = new ArrayList<>();
86         File fileDic = new File(path);
87         File[] files = fileDic.listFiles();
88         for (File file : files) {
89             if ("1".equals(fileType)) {
90                 if (file.isFile()) {
91                     fileList.add(file.toString());
92                 }
93             }
94             if ("0".equals(fileType)) {
95                 if (file.isDirectory()) {
96                     fileList.add(file.toString());
97                 }
98             }
99         }
100         return fileList;
101     }
102
103     /**
104      * @param path
105      * @MethodName getFolderFiles
106      * @Description 递归获取所有包括子文件夹的文件
107      * @Author ChenJiaHe
108      * @Date 2019/9/17 16:11
109      * @Since JDK 1.8
110      */
111     public static void getAllFileName(String path, List<String> listFileName) {
112         try {
113             File file = new File(path);
114             File[] files = file.listFiles();
115             String[] names = file.list();
116             if (names != null) {
117                 String[] completNames = new String[names.length];
118                 for (int i = 0; i < names.length; i++) {
119                     completNames[i] = path + names[i];
120                 }
121                 listFileName.addAll(Arrays.asList(completNames));
122             }
123             for (File a : files) {
124                 // 如果文件夹下有子文件夹,获取子文件夹下的所有文件全路径。
125                 if (a.isDirectory()) {
126                     getAllFileName(a.getAbsolutePath() + "\\", listFileName);
127                 }
128             }
129         } catch (Exception e) {
130             e.printStackTrace();
131         }
132     }
133
134     /**
135      * 读取文件内容,作为字符串返回
136      */
137     public static String readFileAsString(String filePath) throws IOException {
138         File file = new File(filePath);
139         if (!file.exists()) {
140             throw new FileNotFoundException(filePath);
141         }
142
143         if (file.length() > 1024 * 1024 * 1024) {
144             throw new IOException("File is too large");
145         }
146
147         StringBuilder sb = new StringBuilder((int) (file.length()));
148         // 创建字节输入流
149         FileInputStream fis = new FileInputStream(filePath);
150         // 创建一个长度为10240的Buffer
151         byte[] bbuf = new byte[10240];
152         // 用于保存实际读取的字节数
153         int hasRead = 0;
154         while ( (hasRead = fis.read(bbuf)) > 0 ) {
155             sb.append(new String(bbuf, 0, hasRead));
156         }
157         fis.close();
158         return sb.toString();
159     }
160
161     /**
162      * 根据文件路径读取byte[] 数组
163      */
164     public static byte[] readFileByBytes(String filePath) throws IOException {
165         File file = new File(filePath);
166         if (!file.exists()) {
167             throw new FileNotFoundException(filePath);
168         } else {
169             ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
170             BufferedInputStream in = null;
171
172             try {
173                 in = new BufferedInputStream(new FileInputStream(file));
174                 short bufSize = 1024;
175                 byte[] buffer = new byte[bufSize];
176                 int len1;
177                 while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
178                     bos.write(buffer, 0, len1);
179                 }
180
181                 byte[] var7 = bos.toByteArray();
182                 return var7;
183             } finally {
184                 try {
185                     if (in != null) {
186                         in.close();
187                     }
188                 } catch (IOException var14) {
189                     var14.printStackTrace();
190                 }
191
192                 bos.close();
193             }
194         }
195     }
196
197
198     /**
199      *  2020-06-29
200      *  cjh
201      * 图片格式判断
202      * */
203     public static boolean imageFormatJudge(MultipartFile firs) {
204         String imageName = firs.getOriginalFilename();
205         //截取格式
206         String suffix =imageName.substring(imageName.lastIndexOf(".") + 1);
207         //格式字母转小写
208         suffix = suffix.toLowerCase();
209         //进行判断
210         if(suffix.equals("png")) {
211             return true;
212         }else if(suffix.equals("jpg")){
213             return true;
214         }else if(suffix.equals("jpeg")){
215             return true;
216         }else {
217             return false;
218         }
219     }
220
221     /**图片上传的方法
222      * 保存到服务器里面的
223      * @param platformIconFile 图片文件
224      * @param unifiedFolder NG指向的前端文件夹(统一文件夹),如:user/local/images/
225      * @param saveFolder 保存到的文件夹,如:/bananer/
226      * @param autoDateFolder 是否生成日期文件夹
227      * @return 图片路径
228      * 2020-06-29 ChenJiaHe
229      */
230     public static String handleFileUpload(MultipartFile platformIconFile,String unifiedFolder,String saveFolder
231             ,boolean autoDateFolder) {
232         String fileName = "";
233         try {
234             if(platformIconFile == null) {
235                 throw new TipsException("请上传图片!");
236             }
237             if(!imageFormatJudge(platformIconFile)) {
238                 throw new TipsException("请上传png、jpg和jpeg格式的图片!");
239             }
240
241             //设置图片大小
242            // String.format("%.1f",platformIconFile.getSize()/1024.0);
243             if(autoDateFolder){
244                 if(saveFolder.endsWith("/")){
245                     saveFolder = saveFolder+dateFormat(new Date(),"yyyyMM")+"/";
246                 }else{
247                     saveFolder = saveFolder+"/"+dateFormat(new Date(),"yyyyMM")+"/";
248                 }
249             }
250             fileName = dateFormat(new Date(),"yyyyMMddHHmmssSSS");
251             if(unifiedFolder.endsWith("/")){
252                 if(saveFolder.startsWith("/")){
253                     saveFolder = saveFolder.replaceFirst("/","");
254                     unifiedFolder  = unifiedFolder + saveFolder;
255                 }else{
256                     unifiedFolder  = unifiedFolder+saveFolder;
257                 }
258             }else{
259                 if(saveFolder.startsWith("/")){
260                     unifiedFolder  = unifiedFolder + saveFolder;
261                 }else{
262                     unifiedFolder  = unifiedFolder+"/"+saveFolder;
263                 }
264             }
265             fileName = saveFolder+fileUp(platformIconFile,unifiedFolder,fileName);
266         } catch (RuntimeException e) {
267             e.printStackTrace();
268         }
269         return fileName;
270     }
271
272     /**
273      * 2020-06-29 ChenJiaHe
274      * @param file             //文件对象
275      * @param filePath        //上传路径
276      * @param fileName        //文件名
277      * @return  文件名
278      */
279     public static String fileUp(MultipartFile file, String filePath, String fileName){
280         String extName = ""; // 扩展名格式:
281         try {
282             if (file.getOriginalFilename().lastIndexOf(".") >= 0){
283                 extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
284             }
285             copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
286         } catch (IOException e) {
287             System.out.println(e);
288         }
289         return fileName+extName;
290     }
291
292     /**
293           * 写文件到当前目录的upload目录中
294           *
295           * @param in
296           * @param fileName
297           * @throws IOException
298           */
299     private static String copyFile(InputStream in, String dir, String realName)throws IOException {
300         File file = new File(dir, realName);
301         file.setWritable(true);
302         if (!file.exists()) {
303             if (!file.getParentFile().exists()) {
304                 file.getParentFile().mkdirs();
305             }
306             file.createNewFile();
307         }
308         org.apache.commons.io.FileUtils.copyInputStreamToFile(in, file);
309         return realName;
310     }
311
312     /**
313      *
314      * @param date 时间
315      * @param format 时间格式
316      * @return 返回的时间格式字符串
317      */
318     public static String dateFormat(Date  date,String format) {
319         SimpleDateFormat df = new SimpleDateFormat(format);//设置日期格式
320         return df.format(date);
321     }
322
323
324     /**
325      * @param stream 文件流
326      * @param saveUrl 保存到的文件夹
327      * @param fileName 文件图片
328      * @return
329      * @throws IOException
330      */
331     public static File inputStreamToFile(InputStream stream,String saveUrl,String fileName) throws IOException {
332         if(saveUrl.endsWith("/")){
333             saveUrl = saveUrl + fileName;
334         }else{
335             saveUrl = saveUrl +"/"+ fileName;
336         }
337         File targetFile = new File(saveUrl);
338         org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, targetFile);
339         return targetFile;
340     }
341
342 }